How to check if data already exists in the table using django - django

I am new with django framework struggling to compare value from the database.
this are my tables in models.py :
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE,)
title = models.CharField(max_length=200)
content = models.TextField()
creationDate = models.DateTimeField(auto_now_add=True)
lastEditDate = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
class Votes(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE,)
post_id = models.ForeignKey(Post, on_delete=models.CASCADE,)
up_vote = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)])
down_vote = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)])
class Meta:
unique_together = (("user","post_id"),)
I have data in the vote tabe like this:
Now what I want is to check in the above table if 'user_id' and 'post_id' already exists in the Votes tabel's rows if the exist throw a message if not add value on upvote or downvote, i gues everyone understand what i want if not please let me know.
something which i tried was this code:
def chk_table():
user_id = request.user
post_id = id
votes_table = Votes.objects.filter(user_id=user_id, post_id= post_id).exists()
return votes_table
but this function is checking in hole table not just in just in one row...

Assuming that, in your urls.py
from django.urls import path
from .views import add_vote
urlpatterns = [
path('post/<int:post_id>/vote/add/', add_vote, name='add-vote'),
]
In your views.py
from django.shortcuts import redirect, render
def add_vote(request, post_id):
if request.method == 'POST':
# receive your POST data here
user_id = request.user.id
post_id = post_id
if not Votes.objects.filter(user_id=user_id, post_id=post_id).exists():
Votes.objects.create(**your_data)
redirect('your-desired-url')
else:
# your logic here

I see you already defined unique_together in Meta so you can use try except
from django.db import IntegrityError
try:
# your model create or update code here
except IntegrityError as e:
if 'unique constraint' in e.message:
# duplicate detected

Related

Django foreign key issue with django-import-export library (IntegrityError at /import/ FOREIGN KEY constraint failed)

I'm relatively new to Django and not an advanced programmer, so please pardon my ignorance.
What is working:
I have a Django application that uses one main model which connects to two secondary models with foreign keys. The application can correctly create companies from template and from admin, and can correctly display the "niche" drop-down field using a foreign key to the Category model and can correctly display the images using a foreign key from the CompanyImage model.
What is not working:
The django-import-export library can correctly import an XLS document from front end and from admin, but ONLY if I disable the Category and CompanyImage model that are relying on foreign keys. The library does import correctly with the default user=models.ForeignKey(User) in my main Company model, but the foreign keys that connect to the secondary models are causing a foreign key error: IntegrityError at /import/ FOREIGN KEY constraint failed.
What I need
The XLS sheet I am importing does not import the fields that use a foreign key, so I would like to disable those fields to avoid the foreign key error. It would be nice to import a niche/category field, but I can do without.
What I've tried
I've spent two days trying to fix this problem.
I've tried reading the django-import-export documentation.
I've tried adding list_filter and exclude in class Meta for the Resource model.
I've read through Dealing with import of foreignKeys in django-import-export.
I've read through foreign key in django-import-export.
I would be very grateful someone can help steer me in the right direction. Thank you.
Models.py
from django.db import models
from django.contrib.auth.models import User
from phonenumber_field.modelfields import PhoneNumberField
#had to use pip install django-phone-verify==0.1.1
from django.utils import timezone
import uuid
from django.template.defaultfilters import slugify
class Category(models.Model):
kind = models.CharField(verbose_name='Business Type',max_length=100,blank=True,)
class Meta:
verbose_name_plural = "Categories"
def __str__(self):
return self.kind
class Company(models.Model):
#BASIC
title = models.CharField(verbose_name='company name',max_length=100,blank=True)
contact = models.CharField(verbose_name='director',max_length=100,blank=True)
phone_number = PhoneNumberField(blank=True)
email = models.EmailField(max_length=200,blank=True)
email_host = models.CharField(max_length=200,blank=True)
website = models.URLField(max_length=200,blank=True)
facebook = models.URLField(max_length=200,blank=True)
memo = models.TextField(blank=True)
niche = models.ForeignKey(Category, default=0000,on_delete=models.SET_DEFAULT)
#UPLOADS
profile_picture = models.ImageField(upload_to='prospects/images/', blank=True)
image = models.ImageField(upload_to='prospects/images/', blank=True)
file = models.FileField(upload_to='prospects/uploads', blank=True)
#TIME
date = models.DateField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
datecompleted = models.DateTimeField(null=True, blank=True) #null for datetime object
#BOOLIANS
important = models.BooleanField(default=False)
cold = models.BooleanField(default=False, verbose_name='these are cold leads')
warm = models.BooleanField(default=False, verbose_name='these are warm leads')
hot = models.BooleanField(default=False, verbose_name='these are hot leads')
#USER
user = models.ForeignKey(User, on_delete=models.CASCADE,null=True,blank=True)
#TEST MODEL
decimal = models.DecimalField(max_digits=5, decimal_places=2, blank=True, default=00.00)
integer = models.IntegerField(blank=True, default=0000)
positive_int = models.PositiveIntegerField(null=True, blank=True, default=0000)
positive_small_int = models.PositiveSmallIntegerField(null=True, blank=True, default=0000)
#ADMIN CONSOLE
class Meta:
verbose_name_plural = "Companies"
def __str__(self):
if self.title == "":
print('empty string')
return "No Name"
elif type(self.title) == str:
return self.title
else:
return "No Name"
# this makes the title appear in admin console instead of object number
class CompanyImage(models.Model):
company = models.ForeignKey(Company, default=None, on_delete=models.CASCADE)
image = models.FileField(upload_to = 'prospects/images/',blank=True)
def __str__(self):
return self.company.title
resource.py
from import_export import resources
# from import_export import fields
from import_export.fields import Field
from import_export.fields import widgets
from .models import Company
from django.utils.encoding import force_str, smart_str
# The following widget is to fix an issue with import-export module where if i import any number from an xls file, it imports as a float with a trailing ,0
#could keep it a number and use trunc function to take away decimal but will make string
class DecimalWidget(widgets.NumberWidget):
def clean(self, value, row=None, *args, **kwargs):
print()
print(f"type of value is {type(value)}")
print()
if self.is_empty(value):
return ""
elif type(value) == float:
new_string = force_str(value)
seperator = '.'
new_string_witout_0 = new_string.split(seperator, 1)[0]
print()
print(f"the new type of value is {type(value)}")
print(f"the new value is {value}")
print()
return new_string_witout_0
else:
print("Aborting! it's not a float or empty string. will just return it as it is.")
return value
print()
print(f"type of value is {type(value)}")
print(f" the value returned is {value}")
print()
class CompanyResource(resources.ModelResource):
title = Field(attribute='title', column_name='name',widget=DecimalWidget())
contact = Field(attribute='contact', column_name='contact',widget=DecimalWidget())
phone_number = Field(attribute='phone_number', column_name='phone',widget=DecimalWidget())
# niche = Field(attribute='niche', column_name='niche',widget=DecimalWidget())
class Meta:
model = Company
exclude = ('niche')
fields = ('id','title','contact','phone_number', 'email','email_host','website','facebook')
export_order = ['id','title','contact','phone_number', 'email','email_host','website','facebook']
# fields = ( 'id', 'weight' )
admin.py
from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from import_export.fields import Field
from import_export import resources
# from import_export import resources
from .models import Company,Category, CompanyImage
from.resources import CompanyResource
class CompanyResource(resources.ModelResource):
class Meta:
model = Company
class CompanyImageAdmin(admin.StackedInline):
model = CompanyImage
class CompanyAdmin(ImportExportModelAdmin):
resource_class = CompanyResource
inlines = [CompanyImageAdmin]
# Register your models here.
admin.site.register(Category)
admin.site.register(Company,CompanyAdmin)
#admin.register(CompanyImage)
class CompanyImageAdmin(admin.ModelAdmin):
pass
views.py
def importcompanies(request):
if request.method == 'GET':
return render(request, 'prospects/import.html')
else:
file_format = request.POST['file-format']
company_resource = CompanyResource()
dataset = Dataset()
new_companies = request.FILES['myfile']
if file_format == 'CSV':
imported_data = dataset.load(new_companies.read().decode('utf-8'),format='csv')
result = company_resource.import_data(dataset, dry_run=True, raise_errors=True)
elif file_format == 'XLSX':
imported_data = dataset.load(new_companies.read(),format='xlsx')
result = company_resource.import_data(dataset, dry_run=True, raise_errors=True)
elif file_format == 'XLS':
imported_data = dataset.load(new_companies.read(),format='xls')
result = company_resource.import_data(dataset, dry_run=True, raise_errors=True)
if result.has_errors():
messages.error(request, 'Uh oh! Something went wrong...')
else:
# Import now
company_resource.import_data(dataset, dry_run=False)
messages.success(request, 'Your words were successfully imported')
return render(request, 'prospects/import.html')
You have CompanyResource defined in two places, so this could be the source of your problem. Remove the declaration from admin.py and see if that helps.
As you say, fields and exclude are used to define which model fields to import. fields is a whitelist, whilst exclude is a blacklist, so you shouldn't need both.
Set up a debugger (if you haven't already) and step through to find out what is going on (this can save days of effort).
If it is still not working, please update your answer and try to be specific about the nature of the issue (see how to ask).

My views.py is returning null from django admin object

I would really appreciate some help on this because I'm completely stuck. I've started up a simple django app (trying to make an instagram clone). However, when I try to display the post objects (which I created in the django admin page) nothing is displayed in index.html, so I tried printing out the objects in the views.py and it's returning to me an empty query set. I don't quite understand what I'm doing wrong and why I can't access the objects? When I print out the username I am able to get that, but then nothing for both post and stream objects. Please I'm so stuck any advice would be appreciated.
views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.template import loader
from django.http import HttpResponse
# Create your views here.
from post.models import post, stream
#login_required
# we are getting all of the string objects that are created for the user
def index(request):
user = request.user
print(user)
posts = stream.objects.filter(user=user)
print(posts)
group_ids = []
#then looping through and getting post id to a list
for posted in posts:
group_ids.append(posted.post_id)
print(group_ids)
#then filtering them so that you can display it in the index
#selecting a specific post by id
post_items = post.objects.filter(id__in=group_ids).all().order_by('-date')
template = loader.get_template('index.html')
context = {'post_items' : post_items}
return(HttpResponse(template.render(context, request)))
models.py
from django.db import models
from django.contrib.auth.models import User
import uuid
# Create your models here.
from django.db.models.signals import post_save
from django.utils.text import slugify
from django.urls import reverse
def user_directory_path(instance,filename):
# this file is going to be uploaded to the MEDIA_ROOT /user(id)/filename
return('user_{0}/{1}'.format(instance.user.id,filename))
class tag(models.Model):
title = models.CharField(max_length = 80, verbose_name = 'tag')
slug = models.SlugField(null = False, unique = True)
class Meta:
verbose_name = 'tag'
verbose_name_plural = 'tags'
# for when people click on the tags we can give them a url for that
# def get_absolute_url(self):
# return(reverse('tags', args = [self,slug]))
def __str__(self):
return(self.title)
def save(self,*args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
return(super().save(*args, **kwargs))
class post(models.Model):
# will create a long id for each post
id = models.UUIDField(primary_key=True, default = uuid.uuid4, editable = False)
image = models.ImageField(upload_to = user_directory_path, verbose_name= 'image', null = True)
caption = models.TextField(max_length = 2000, verbose_name = 'caption')
date = models.DateTimeField(auto_now_add = True)
tags = models.ManyToManyField(tag, related_name='tags')
user = models.ForeignKey(User, on_delete=models.CASCADE)
likes = models.IntegerField()
def get_absolute_url(self):
return reverse('postdetails', args=[str(self.id)])
# def __str__(self):
# return(self.user.username)
class follow(models.Model):
follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower')
following = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following')
class stream(models.Model):
following = models.ForeignKey(User, on_delete=models.CASCADE, related_name='stream_following')
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(post, on_delete=models.CASCADE)
date = models.DateTimeField()
def add_post(sender, instance,*args, **kwargs):
# here we are filtering all the users that are following you
post = instance
user = post.user
followers = follow.objects.all().filter(following=user)
for follower in followers:
streams = stream(post=post, user=follower.follower, date = post.date, following = user)
streams.save()
post_save.connect(stream.add_post, sender=post)
output from print statements
user
<QuerySet []>
[]
I figured it out. It wasn't an issue with the code, but the way that I was creating posts in the admin panel. So because you can only view posts from users that you are following, the posts that I was creating weren't showing up. So I had to create another user, and follow that user, then have the new user post something. Then the post shows up in the page!

How to make provide views and specify which users can GET it

I created the following model, with an author who is the user that created it and Title and description, with few other fields.
from django.db import models
from django.conf import settings
from django.utils import timezone
# Create your models here.
class Author(models.Model):
name = models.CharField(max_length=200)
added_by = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=200)
description = models.CharField(max_length=300)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
added_by = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
created_date = models.DateTimeField(default=timezone.now)
# 🔴 who_can_see
who_can_see = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name='tweet_user', blank=True)
def __str__(self):
return self.title
now I want to filter books based on who_can_see and auther
My question is: how to modify this books = Book.objects.filter(added_by=user) in order to get only the posts that have the authenticated username included in the who_can_see field.
in models.py i created this field to add the usernames that can see the view who_can_see = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='tweet_user', blank=True), but I don't know how to filter views based on them, also users can see all books even when they are not loggedin
#api_view(["POST"])
#csrf_exempt
#permission_classes([IsAuthenticated])
def add_book(request):
print({"request.data": request.data})
payload = request.data
user = request.user
try:
author = Author.objects.get(id=payload["author"])
book = Book.objects.create(
title=payload["title"],
description=payload["description"],
added_by=user,
author=author,
who_can_see=payload["who_can_see"] # 🔴
)
serializer = BookSerializer(book)
return JsonResponse({'books': serializer.data}, safe=False, status=status.HTTP_201_CREATED)
except ObjectDoesNotExist as e:
return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND)
except Exception:
return JsonResponse({'error': 'Something terrible went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
#api_view(["GET"])
#csrf_exempt
#permission_classes([IsAuthenticated])
def get_books(request):
# here maybe I need other arguments than request to get the other filed, in order to create if statements.
user = request.user.id
# books = Book.objects.filter(added_by=user)
books = Book.objects.filter(who_can_see=user, added_by=user) # 🔴 after i created this user who are not logged in can see the all private books.
serializer = BookSerializer(books, many=True)
return JsonResponse({'books': serializer.data}, safe=False, status=status.HTTP_200_OK)
You have to write query in which you have to check for which book current user is in who_can_see field. You can write this like this.
from django.db.models import Q
current_user = request.user
books = Book.objects.filter(Q(Q(added_by=user) | Q(who_can_see=current_user)))
if you want to get books for which who_can_see is empty
books = Book.objects.filter(Q(Q(added_by=user) | Q(who_can_see=current_user) | Q(who_can_see=None)))

Query for retrieve data with user fk Django 1.11

I'm trying to retrieve data from user. I have my model like this:
from django.db import models
from django.contrib.auth.models import User
Create your models here.
class informacionFacturacion(models.Model):
usuario = models.ForeignKey(User)
apellidos = models.CharField(max_length=100, default="editar")
nombres = models.CharField(max_length=100, default="editar")
telefono = models.CharField(max_length=100, default="editar")
email = models.EmailField(default="editar", null=False)
direccion_1 = models.CharField(max_length=100, default="editar")
direccion_2 = models.CharField(max_length=100, null=True, blank=True)
provincia = models.CharField(max_length=100, default="editar")
ciudad = models.CharField(max_length=100, default="editar")
codigoPostal = models.CharField(max_length=100, default="editar")
empresa = models.CharField(max_length=100, default="editar")
def __str__(self):
return self.usuario
My form for update user information:
from .models import informacionFacturacion
class informacionFacturacionForm(ModelForm):
class Meta:
model = informacionFacturacion
fields = [
"usuario",
"apellidos",
"nombres",
"telefono",
"email",
"direccion_1",
"direccion_2",
"provincia",
"ciudad",
"codigoPostal",
"empresa",
]
And in my view I have my query like this
from django.contrib.auth.decorators import login_required
from .models import informacionFacturacion
from .forms import informacionFacturacionForm
#login_required
def datosPersonales(request):
form = informacionFacturacionForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
query = informacionFacturacion.objects.filter(usuario=request.user)
context = {
"titulo": "Datos personales | Cadenas Giordanino S.R.L" + request.user.username,
"body_class": "class= sidebar_main_open sidebar_main_swipe",
"form": form,
"infoFacturacion": query,
}
template = "micuenta/datosPersonales.html"
return render(request, template, context)
And this QuerySet is empty.
I need to retrieve this data in the user profile
**UPDATE: ** Full code on post.
**UPDATE 2: ** For displaying the user data on profile, im using a "For loop". This data, is retrieved in "value=" attr of html inputs. If the user has no data, the form dosnt show.
This is the way I wanna show the data. I populated this form from the same form u see here.
Here's when i enter for first time to my profile with no data
Thanks a lot.
Are you sure that request.user is the user you've linked your anotherModel to? If you aren't currently logged in then request.user will be an instance of AnonymousUser. See more in the Documentation: https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest.user
You can use the Django Shell for testing your models:
$ python manage.py shell
Then make some models:
from django.contrib.auth.models import User
from models import AnotherModel
# Grab a User
user = User.objects.first()
# Create a new anotherModel, linking the user
my_model = AnotherModel(
user=user,
address="whatever"
)
my_model.save()
my_model.user == user
>>> True

Foriegnkey issue while submitting the form

This post extends the error while submitting data in the form django
model.py
from django.db import models
# Create your models here.
class Profile(models.Model):
name = models.CharField(max_length=50, primary_key=True)
assign = models.CharField(max_length=50)
doj = models.DateField()
class Meta:
db_table= 'profile'
def __unicode__(self):
return u'%s' % (self.name)
class working(models.Model):
w_name =models.ForeignKey(Profile, db_column='w_name')
monday = models.IntegerField(null=True, db_column='monday', blank=True)
tuesday = models.IntegerField(null=True, db_column='tuesday', blank=True)
wednesday = models.IntegerField(null=True, db_column='wednesday', blank=True)
class Meta:
db_table = 'working'
def __unicode__(self):
return u'%s ' % ( self.w_name)
view.py
# Create your views here.
from forms import *
from django import http
from django.shortcuts import render_to_response, get_object_or_404
def index(request):
obj=working()
obj.w_name='X'
obj.Monday=1
obj.Tuesday=2
obj.Wednesday =3
obj.save()
return http.HttpResponse('Added')
Here i want to insert the data directly into table ,if person click on http://127.0.0.1:8000/
But it throws below error any thoughts ??
Exception Type: ValueError at /
Exception Value: Cannot assign "u'x'": "working.w_name" must be a "Profile" instance.
I thought you were saying you wanted to inject values into a form?
In this case, it's clear (see it's better than comments), you need to pass in a Profile instance to your working object just as we did in the form clean method in your other post.
def index(request):
try:
profile = Profile.objects.get(pk='X')
except Profile.DoesNotExist:
assert False # or whatever you wish
obj=working()
obj.w_name= profile
obj.Monday=1
obj.Tuesday=2
obj.Wednesday =3
obj.save()
return http.HttpResponse('Added')