Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: When I delete item from one of the user's shopping cart, that same item gets deleted from every user's shopping cart
Using python 3.7 When I add item to the cart, the item gets added individually to each user, but I have delete button on the cart details page and the function in views.py looks like this: def delete_cart_item(request, item_id): user_profile = get_object_or_404(User_Profile, user=request.user) shopping_cart = user_profile.shopping_cart_set.first() item = shopping_cart.items.get(pk=item_id) item.delete() return redirect('Sales:cart_details') Those are my models: class User_Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Item(models.Model): item_name = models.CharField(max_length=200) item_price = models.IntegerField() item_description = models.CharField(max_length=300) item_bought_price = models.IntegerField() stock_level = models.IntegerField() restock_level = models.IntegerField() class Cart_Item(models.Model): item = models.OneToOneField(Item, on_delete=models.SET_NULL, null=True) class Shopping_Cart(models.Model): ref_code = models.CharField(max_length=15) owner = models.ForeignKey(User_Profile, on_delete=models.SET_NULL, null=True) items = models.ManyToManyField(Cart_Item) What is the issue here? I tried changing on_delete=models.SET_NULL of Cart_Item to on_delete=models.CASCADE but that didn't seem to change anything. There also is a weird issue that when the cart is empty and I add the first item, that item cannot be deleted from the page, I can delete it from shell though. -
Django : Issue with MultiValueDictKeyError with download function
I would like to get your help in order to improve my code and get the possibility to download document thanks to 2 different ways. Explanations: The first method let to check some documents and user has to fill an email field. Once it done, a modal appears with pre-filled fields according to previous email address because a queryset is executed with a filter on email adress This is the main process to download documents. The second method is different. I generate an unique hyperlink with the document id in the url. But through this way, I don't need the email address as previously. My codes: This is my model.py file : class Document(models.Model): code = models.CharField(max_length=25, verbose_name=_('code'), unique=True, null=False, blank=False) language = models.CharField(max_length=2, verbose_name=_('language'), choices=LANGUAGE_CHOICES, null=False, blank=False) format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES, null=False, blank=False) title = models.CharField(max_length=512, verbose_name=_('title'), null=False, blank=False) publication = models.ForeignKey(Publication, verbose_name=_('publication title'), related_name='documents') upload = models.FileField(upload_to='media/files/', validators=[validate_file_extension], verbose_name=_('document file'), null=False, blank=False) class Meta: verbose_name = _('document') verbose_name_plural = _('documents') class Customer(EdqmTable): email = models.EmailField(max_length=150, verbose_name=_('e-mail'), null=False) first_name = models.CharField(max_length=70, verbose_name=_('first name'), null=False) last_name = models.CharField(max_length=70, verbose_name=_('last name'), null=False) country = models.ForeignKey(Country, verbose_name=_('country')) institution = models.CharField(max_length=255, verbose_name=_('institution'), null=True) class Meta: verbose_name = _('customer') verbose_name_plural = _('customers') def … -
Deploying Seprate React Frontend and Django DRF API
I have a react frontend made with create-react-app to deploy a production build of this I just do npm run build. My app uses a Django Rest FrameWork API backend. How can I setup the app for deployment on a single server. Is there a way I can store the React Frontend and route to it in Django and have requests from the Frontend hit a api/ view or endpoint. What are the best strategies for deploying something like this or is it better to host the Frontend and Backend desperately on different servers? -
how to make sure my django app1 url is not accessible by app2
My problem is I have a app called guardian, which has login, register features. Now there is another app called tutor, which also has the same. and when I login to guardian it automatically logs in tutor app also. -
How to change Django content based on different templates
I created a model to handle templates in Django, different templates, now the issue is that how do I serve different content in the html tags using Django context since the p tags and div tags content for each template are different using context processing -
Django rendering multiple images using inlineformset
A django newbie here, I am trying to enable uploading multiple images in one classified post. I am using a generic class-based view, CreateView, but the formset for images are not rendered in my html, only the ClassifiedForm and the submit/publish button. Note this is a duplicate for this question but it was not answered. My files are like this (Just the important parts, I have skipped some code chunks). models.py class Classified(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODE, on_delete=models.SET_NULL) timestamp = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=255, null=False) content = models.CharField(max_length=1000) class ClassifiedImages(models.Model): classified = models.ForeignKey(Classified, default=None,\ on_delete=models.CASCADE, related_name='classified_images') images = models.ImageField(upload_to=get_image_filename, verbose_name='Image') forms.py class ClassifiedForm(forms.ModelForm): class Meta: model = Classified fields = ["title", "content"] ImagesFormSet = inlineformset_factory(Classified, ClassifiedImages, fields =["images"], extra=5) I just think this views.py is wrong but it goes like this class CreateClassifiedView(CreateView): model = Classified message = _("Your classified has been created.") form_class = ClassifiedForm template_name = 'classifieds/classified_create.html' def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) images_form = ImagesFormSet() return self.render_to_response( self.get_context_data(form=form, images_form=images_form )) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) images_form = ImagesFormSet(self.request.POST) if (form.is_valid() and images_form.is_valid()): return self.form_valid(form, images_form) else: return self.form_invalid(form, images_form) def … -
How to test excel file upload in django
I've written a view which handles the excel file upload, now I'm trying to write unit test for the business logic but I'm stuck on excel file mocking. can someone help me with that? -
Django UNIQUE constraint
Django UNIQUE constraint failed error django.db.utils.IntegrityError: UNIQUE constraint failed while I am using the unique together constraint in the models. How can I use it properly? -
Value not getting saved in django model
I have made two models which are as follows: class itemsSearched(models.Model): searched_items = models.CharField(max_length=120) def __str__(self): return self.searched_items class VisitorInfo(models.Model): user_id = models.CharField(max_length=120) items_searched = models.ManyToManyField(itemsSearched,blank=True) I want to save value tshirt in visitorInfo model. Here is the view for this def get_req(request): event = request.GET['e'] if event == 'pv': x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') check_user(request,ip) elif event == 'pp': visitor = VisitorInfo.objects.get(user_id=request.GET['duid']) visitor.active = True print(visitor.active) visitor.save() elif event == 'ue': u_id = request.GET['duid'] tz = request.GET['tz'] url = request.GET['url'] link = request.GET['ue_pr'] #ue_pr is the property of unstructured event of the type json. o = json.loads(link) print(o) if(o['data']['data']['elementId']=='nf-field-1'): name = o['data']['data']['value'] print("Name: "+ name) visitor= VisitorInfo.objects.get(user_id=u_id) visitor.name = name visitor.save() elif(o['data']['data']['elementId']=='s'): searched_item = int(o['data']['data']['value']) print("Searched: "+ searched_item) #6 print("Type of searched_item " + type(searched_item)) #7 visitor= VisitorInfo.objects.get(user_id=u_id) visitor.items_searched.add(searched_item) visitor.save() For the sake of clarity I printed 'o' which is a python dictionary parsed from json.Here is the what i have got {'schema': 'iglu:com.snowplowanalytics.snowplow/unstruct_event/jsonschema/1-0-0', 'data': {'schema': 'iglu:com.snowplowanalytics.snowplow/change_form/jsonschema/1-0-0', 'data': {'formId': 'FORM', 'elementId': 's', 'nodeName': 'INPUT', 'type': 'search', 'elementClasses': ['search-field'], 'value': 'tshirt'}}} I want to save the value 'tshirt' in visitor info but i am getting the following error. Traceback (most recent call last): … -
importing csv in djang
i am trying to import csv file into db from manage.py shell but it is giving me error import csv with open(r"C:\Users\yousa\Desktop\xp\exp\Dist_Extended_TissuesWise_ClusteredAnnotated_21nov2018_qaz.csv", 'r') as f: reader = csv.reader(f) lines = list(reader) del lines[0] objects = [] for line in lines: obj =Maize_clustert() obj.chromosome = int(line[0]) obj.cluster_start = int(line[1]) obj.cluster_end = int(line[2]) obj.strand = line[3] obj.pac = int(line[4]) obj.pac_suppoort = int(line[5]) obj.cluster_support = int(line[6]) obj.region = line[7] obj.gene_id = line[8] obj.transcript_id = line[9] obj.distance = line[10] obj.transcript_code = line[11] obj.gene_cord = line[12] obj.utr_length = int(line[13]) obj.gene_biotype = line[14] obj.cluster_size = int(line[15]) obj.number_pas = int(line[16]) obj.zygote = int(line[17]) obj.sperm = int(line[18]) obj.egg = int(line[19]) obj.root = int(line[20]) obj.embryo = int(line[21]) obj.basal = int(line[22]) obj.ear = int(line[23]) obj.apical = int(line[24]) obj.ovule = int(line[24]) objects.append(obj) Maize_clustert.objects.bulk_create(objects) while runnig this code in manage.py shell it give me result Traceback (most recent call last): File "<input>", line 8, in <module> NameError: name 'Maize_clustert' is not defined while in models.py i have created full model of my data is there any alternative way or i am doing it wrong kindly help me in it -
Django filter - Multiple value
so a have little problem: genres = (x, y, z,...) search = Movie.filter(Q(genres=x) | Q(genres=y| ...) I can filter by that in django and have in one variable like this but i dont know how many variables will genres have. So it is possible to that at all? -
how to add custom error messages in modelform widgets in django
these are fields of the model form class Meta: model = Employee exclude = ('user', 'created_by', 'is_deleted', 'created') theses are the widgets widgets = { 'first_name': forms.TextInput(attrs={'placeholder': _('First name')}), 'last_name': forms.TextInput(attrs={'placeholder': _('Last name')}), 'house_name': forms.TextInput(attrs={'placeholder': _('House name / flat No')}), 'street_name': forms.TextInput(attrs={'placeholder': _('Street Name / No')}), 'locality_name': forms.TextInput(attrs={'placeholder': _('Locality Name / No')}), 'pin_code': forms.TextInput(attrs={'placeholder': _('Zip Code')}), } -
"badly formed hexadecimal UUID string" when filtering a GraphQL query on multiple IDs (Graphene-Django)
I have Django models Photo and Tag which have a many-to-many relationship joined through the model PhotoTag. This is the relevant bit from models.py - note they inherit from UUIDModel so have UUIDs as the primary key rather than the default auto-increment ID. Models class Photo(UUIDModel): taken_at = models.DateTimeField(null=True) taken_by = models.CharField(max_length=128, blank=True, null=True) aperture = models.DecimalField(max_digits=3, decimal_places=1, null=True) exposure = models.CharField(max_length=8, blank=True, null=True) iso_speed = models.PositiveIntegerField(null=True) ... class Tag(UUIDModel): name = models.CharField(max_length=128) ... class PhotoTag(UUIDModel): photo = models.ForeignKey(Photo, related_name='photo_tags') tag = models.ForeignKey(Tag, related_name='photo_tags') ... For the Graphene-Django schema I have two filters defined for all_photos - fetching photos by tag names and fetching by tag ids where tag is assigned through the photo_tags relationship. The schema definition is below - photo_tags__tag__id = graphene.String() is my attempt to prevent the error badly formed hexadecimal UUID string and I hoped that making it a graphene.String() would allow it to be split. Schema class CustomNode(graphene.Node): class Meta: name = 'Node' @staticmethod def to_global_id(type, id): return id class PhotoInterface(graphene.Interface): photo_tags__tag__id = graphene.String() class PhotoNode(DjangoObjectType): class Meta: model = Photo interfaces = (CustomNode, PhotoInterface) class PhotoFilter(django_filters.FilterSet): class Meta: model = Photo fields = { 'photo_tags__tag__id': ['exact', 'in'], 'photo_tags__tag__name': ['exact', 'icontains', 'in'], } class Query(object): … -
Django ForeignKey Model Form
I'm newbie on Django. I have two model and one of this model have Foreign Key. I'm using Model Form in forms and when I fill the form my foreign key field return null. What I want is when I fill the form foreign key field, fill according to the pointed out by the foreign key. Models: class customerInfo(models.Model): customerName = models.CharField(max_length = 50) customerContent = models.TextField(max_length = 50) createdDate= models.DateTimeField(auto_now_add = True) def __str__(self): return self.customerName class productInfo(models.Model): username = models.CharField(max_length = 50) passwd = models.CharField(max_length = 50) destIp = models.CharField(max_length = 50) hostname = models.CharField(max_length = 50) productName = models.CharField(max_length = 50) customer = models.ForeignKey(customerInfo,on_delete = models.CASCADE,null=True) def __str__(self): return self.productName Forms: class customerForm(forms.ModelForm): class Meta: model = customerInfo fields = ( "customerName", ) class addProductForm(forms.ModelForm): class Meta: model = productInfo fields = ( "productName", ) class productInfoForm(forms.ModelForm): class Meta: model = productInfo fields = ( "username", "passwd", "destIp", "hostname", ) Views: @login_required(login_url = "/") def addCustomer(request): form = customerForm(request.POST or None) content = {"form" : form,} if form.is_valid(): form.save() customerName = form.cleaned_data['customerName'] return redirect("addproduct") else: return render(request,"addcustomer.html",content) @login_required(login_url = "/") def addProduct(request): form = addProductForm(request.POST or None) content = {"form" : form} if form.is_valid(): global productName productName … -
Validate each value of an ArrayField of emails in Django
I am using PostgreSQL with Django and am trying to use ArrayField(models.EmailField(max_length=200)) but i am ending up with an 500 error code(TypeError) when giving invalid email address. #models.py billing_emails = ArrayField(models.EmailField(max_length=200)) company = models.OneToOneField(Company, on_delete=models.CASCADE) How can i validate each email in the ArrayField.I have tried writing validate method in both serializer and models....but nothing helped..What is the right way to validate ArrayFields.I am using django 2.1 and python 3.6 Thanks in advance -
how to access non defined database in django?
I have a problem with my application. i dont how to access non defined database in Django. where in my application user creates his own database if they needed. but Django cannot support database which is not defined. how to solve this issue. -
Why is Django blog app throwing FileNotFoundError / Errno2 No such file or directory?
I have a Django based blog application that is currently connected to Heroku. Media files are being served from S3 Bucket AWS and are displayd on my index page: Image of my index page The issue arises when I attempt to update the image in Profile OR create a new Profile OR when I am attempting to log into a profile that has an image stored on my s3 bucket, I get the error: FileNotFoundError at /login/ [Errno 2] No such file or directory 'profile_pics/Screen_Shot_2018-09-30_at_6.51.47_PM.png' AND notice this code near the bottom of the error: /app/users/signals.py in save_profile instance.profile.save() ... ▶ Local vars /app/users/models.py in save img.save(self.image.name) ... ▶ Local vars /app/.heroku/python/lib/python3.6/site-packages/PIL/Image.py in save fp = builtins.open(filename, "w+b") I am also using PIL to resize the image in my models.py file: from django.db import models from django.contrib.auth.models import User from PIL import Image from django.core.files.storage import default_storage as storage class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, **kwargs): super().save() #img = Image.open(self.image.path) img = Image.open(storage.open(self.image.name)) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.name) Just for context this is my settings.py: import os # Build paths … -
Nested Serializer Problem in showing reverse
I defined this model: class city (models.Model): city_name = models.CharField(max_length=100) state = models.ForeignKey(state,related_name='state', on_delete=models.CASCADE) def __str__(self): return self.city_name and this serializer: class citySerializers(serializers.ModelSerializer): class Meta: model = city fields = ('city_name') If I add the state to my serializers field it shows me state_id of the table but I want it to show me state_name(another field of the state table ) I found this tutorial:https://www.django-rest-framework.org/api-guide/relations/ but here inside parent model shows child model item, I want inside child model show parent name(reverse of what tutorial do) how can I do? -
TemplateDoesNotExist at /board/boards
I got this error during the python django project I do not understand why the template does not connect. Please let me know which part of the error it is and let me know how to fix it. How can I to do? Attach an error picture. enter image description here settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] These are my project sub-lists /mysite /board /migrations /templates /board board_list.html board_detail.html search.html __init__.py admin.py apps.py forms.py models.py tests.py urls.py views.py /mysite __init__.py settings.py urls.py views.py wsgi.py /static css js image /templates base.html main.html db.sqlite3 manage.py /mysite/mysite/urls.py from django.contrib import admin from django.conf.urls import url, include from .views import MainHome urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', MainHome.as_view(), name='main'), url(r'^board/', include('board.urls', namespace='board'), ] /mysite/board/urls.py from django.conf.urls import url from .views import * from mysite.views import MainHome app_name = 'board_app' urlpatterns = [ url(r'^$', MainHome.as_view(), name='main'), url(r'^search/$', SearchFormView.as_view(), name='search'), url(r'^boards/$', BoardList.as_view(), name='board_list'), url(r'^boards/(?P<slug>[-\w]+)/$', BoardDetail.as_view(), name='board_detail'), ] /mysite/borad/views from .models import Board from django.views.generic import ListView --- skip --- class BoardList(ListView): model = Board template_name = 'board_list.html' content_object_name = 'boards' paginate_by = 10 --- skip --- -
Uploading images to amazon s3 using boto3 from django
import boto3 from botocore.client import Config ACCESS_KEY_ID = 'XXXXXXXXXXXXXXXX' ACCESS_SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXX' BUCKET_NAME = 'https://s3.amazonaws.com/test-dev-bkt' data = open('/home/kuliza270/Desktop/workspace/hdfc-csrm-backend/webapp/statics/img/headerLogoNew.jpg', 'rb') s3 = boto3.resource( 's3', aws_access_key_id=ACCESS_KEY_ID, aws_secret_access_key=ACCESS_SECRET_KEY, config=Config(signature_version='s3v4') ) s3.Bucket(BUCKET_NAME).put_object(Key='logo.jpg', Body=data) print ("Done") -
How use python-docx to stream a file from template
Ok so right now I have a function in my django app that creates a word document like so: def form_view(request): if request.method == 'POST': #do a bunch of things context = { 'model_1' : model_1, } in_template = "Forms/mytemplate.docx" doc = DocxTemplate(in_template) doc.render(context) out_filename = "outfile.docx" http_word_response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') http_word_response['Content-Disposition'] = 'attachment; filename=%s' % out_filename doc.save(http_word_response) return http_word_response else: return render( request, 'mysite/form.html', context) So right now, the file is served up as the http_word_response variable and it works great I want to change this so that the file is actually created and saved into S3, but I'd like to not save the file locally first and just use the stream function of the python-docx package: https://python-docx.readthedocs.io/en/latest/user/documents.html#opening-a-file-like-document Here's the sample it gives: with open('foobar.docx', 'rb') as f: source_stream = StringIO(f.read()) document = Document(source_stream) source_stream.close() ... target_stream = StringIO() document.save(target_stream) I'm not sure how to translate that sample into reading in my template file and outputting a file/object I can then send to S3 and do something with. My best guess would start like this: with open(in_template, 'rb') as f: source_stream = StringIO(f.read()) doc = DocxTemplate(source_stream) source_stream.close() target_stream = StringIO() document.save(target_stream) But then I get confused on where my doc.render(context) … -
Why does the PATCH of the HTTP method run the model save() method?
I use serializers.ModelSerializer and viewsets.ModelViewSet of Django REST Framework in my REST API. While I was testing, I found out that the PATCH of HTTP method was running model save(). I know PATCH is for updating data, Why DRF use save() instead of update()? -
Async await in django channels cannot get object with id
My consumers.py: async def user_taskcompleted(self, event): me = User.objects.get(username=event['username']) print("ME",me) mentor=me.mentor print("MY MENTOR", mentor) id_task =event['task'] print("GETTING ID",id_task) notification = event['username'] + ' Completed new Task ' + event['title'] print("notification", notification) task = await Task.objects.get(id=id_task) obj = await self.create_notification_to_trainer(me,notification,task) obj.receiver.add(mentor) await self.send_json(event) print("Got message {} at {}".format(event, self.channel_name)) @database_sync_to_async def create_notification_to_trainer(self, sender,notification,task): return Notification.objects.create(sender=sender ,notification=notification,task=task) My signals.py: @receiver(post_save, sender=Task) def create_task_notification(sender, instance, created, **kwargs): if Task.objects.filter (student=instance.student,student__mentor__isnull=False).exists(): if created: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( "gossip", {"type": "user.taskcompleted", "event": "New Task", "task": instance.id, "username": instance.student.username, "title": instance.title, "mentor": instance.student.mentor.username }) print("TASK ID",instance.id) else: print("NO TRAINER") Im trying to save data to the model in my consumers.py to save a notification on a Task save.The problem is that im not able to get the task using the task id in my consumers.py.It shows Task matching query does not exist in my terminal. THe print statements for all other fields are showing in my terminal and im also able to get the correct task id returned As shown in my terminal: TASK ID 323 ME mohitharshan123 MY MENTOR rohitharshan GETTING ID 323 notification mohitharshan123 Completed new Task safasfa The error is showing at Task.objects.get(id=id_task) -
Silencing exceptions in `makemigrations` can be silenced by in `check`, Django. 2.0
Using a version of django-proxy-overrides, I'm overriding a field in a Proxy model that appears a the base model. I'm using Django 2.0 This causes Django's system-check framework to complain, but in my settings file I have set: SILENCED_SYSTEM_CHECKS = ["fields.E305", "fields.E304", "models.E006", "models.E017"] so python manage.py runserver works fine (and the overriding works beautifully). However, when I run python manage.py makemigrations, Django raises an exception complaining about the clash in names: django.core.exceptions.FieldError: Local field 'person' in class 'ProxyBillSponsorship' clashes with field of the same name from base class 'BillSponsorship'. Is there anyway around this? I have tried setting class Meta: managed=False on the the proxied models in the hope that makemigrations would ignore these models, but no luck. -
django:ModuleNotFoundError: No module named 'pure_pagination'
I used "pip install django-pure-pagination", and regiter "pure_pagination" into seetings.py. By use "help('pure_pagination')", I can find the module. But when I debug it on the PycharmIDE. It showes "ModuleNotFoundError: No module named 'pure_pagination' ". enter image description here enter image description here