Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django +2 ImportError: cannot import model
Hi have been working with Django and i want to have relations bettwen model i have the following structure on posts/models.py from django.db import models class Post(models.Model): (SKIP ATTRIBUTES) and then on comments/model.py from django.db import models from posts.models import Post class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') In a nutshell im trying to import posts model into comment model and i get the error that cannot import name 'Post' from 'posts.models , how should import posts model to avoid this issue ? from posts.models import Post ImportError: cannot import name 'Post' from 'posts.models -
Requiring a photo during user registration without using a custom user model in Django
So, I'm creating a dating app from scratch in Django. First project, and new to programming. I want to force a user to upload a photo during registration. I tried doing this with only extending the user model, but I looked around and tried different things but couldn't figure it out so I decided to create a custom user model. However, I am running into problems left and right, and I think that I am over contemplating things by adding a custom user model. How can I force a user to upload a photo during registration by extending the normal User model? Edit: If I am wrong, and it is indeed easier and better to keep the custom user model, please let me know and why. Models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager, User class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): if not email: raise ValueError("You must creat an email") if not username: raise ValueError("You must create a username!") if not description: raise ValueError("You must write a description") if not photo: raise ValueError("You must upload a photo") user = self.model( email=self.normalize_email(email), username = username, description= description, photo= photo, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email,description,photo, password): … -
Top-level StreamBlock within StreamField doesn't render in template
I'm attempting to use a StreamBlock like the last snippet in the section of the docs here, as the only argument to a StreamField. It's working perfectly in the Wagtail admin, but when trying to render in the template nothing appears. I tried using the default template and just include_block, but nothing is rendered. I also tried using a custom template and include_block, and the custom template is hit, but I haven't been able to render anything useful from there. I reverted to trying to use the default template in the following code. home/models.py: from django.db import models from wagtail.core.models import Page from wagtail.core.fields import StreamField from wagtail.admin.edit_handlers import StreamFieldPanel from home.blocks import HeroImageStreamBlock class HomePage(Page): hero_image = StreamField(HeroImageStreamBlock( block_counts={ 'hero_button': {'max_num': 1}, 'is_active': {'max_num': 1}, 'is_randomized': {'max_num': 1}, } ) , blank=True ) content_panels = Page.content_panels + [ StreamFieldPanel('hero_image'), ] home/blocks.py: from wagtail.core import blocks from wagtail.images.blocks import ImageChooserBlock class HeroButtonBlock(blocks.StructBlock): button_text = blocks.CharBlock(required=False) button_page = blocks.PageChooserBlock(required=False) button_url = blocks.URLBlock(required=False) is_active = blocks.BooleanBlock(required=False, help_text="""When checked, this hero button is active. NOTE: Only the first active hero button will be displayed.""") class Meta: icon = "link" class HeroTextBlock(blocks.StructBlock): hero_text = blocks.CharBlock(required=False) is_active = blocks.BooleanBlock(required=False, help_text="""When checked, this hero text is … -
ModelForm with foreignkey field is not being saved
I'm trying to save a ModelForm with foreignkey field from another model. But somehow the data is not being saved. The primary key of the foreignkey field in the Problem models is from Biodata models index.html form is loaded with session['patient'] value that should be the value of the foreignkey in the Problem models upon creation of new item. Upon submitting the form, it says the new item is successfully added, but at the backend, it wasn't saved at all. Here's the code : models.py class Biodata(models.Model): lastname = models.CharField(max_length=50) firstname = models.CharField(max_length=50) dob = models.DateField() sex = models.CharField(max_length=10) address = models.CharField(max_length=100,blank=True) suburb = models.CharField(max_length=40,blank=True) state = models.CharField(max_length=50,blank=True) postcode = models.CharField(max_length=6,blank=True) def __str__(self): return self.firstname + " " + self.lastname class Problems(models.Model): biodata = models.ForeignKey(Biodata, on_delete = models.CASCADE, default=None) problem = models.CharField(max_length=200) notes = models.CharField(max_length=300) status = models.CharField(max_length=30) date = models.CharField(max_length=10) def __str__(self): return self.problem views.py def problem_add(request): patient_id = request.session['patient'] form = ProblemForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.Biodata = Biodata.objects.get(id=patient_id) instance.save messages.success(request,('Problem added')) return redirect('/crud/index/') else : messages.success(request,('There is error in the form')) return redirect('/crud/index/') forms.py class ProblemForm(forms.ModelForm): STATUS = [('S','Stable'),('U','Unstable'),('I','Inactive'),('O','Ongoing Dx.')] problem = forms.CharField(label='',max_length=50, widget=forms.TextInput(attrs={'placeholder':'Problem'})) notes = forms.CharField(label='', widget=forms.Textarea(attrs={'rows':4,'placeholder':'Notes'})) status = forms.ChoiceField(label='', widget=forms.Select(attrs={'placeholder':'Status'}), choices=STATUS) date = forms.DateField(label='', … -
Django Admin and Cloudinary : ValueError: Must supply api_key
Objective: to be able to upload files from the Django Admin, to Cloudinary I pip installed cloudinary, but don't know where to import the chunk of code below. I know how to create model class, which then in the admin, i can create instances i.e blog class, i can create blog articles, but where would I go into to handle the logic for uploading? According to the docs, I need to add this config script, in any HTTP method, but from what I know, Django Admin handles it automatically. But I know this can be done because i've checked out their tutorial and i was able to upload images from Django Admin cloudinary.config( cloud_name=os.environ.get('projname'), api_key=os.environ.get('123'), api_secret=os.environ.get('abc'), secure=True ) models.py class Media(models.Model): create_time = models.DateTimeField(auto_now_add=True) title = models.CharField("Title (optional)", max_length=200, blank=True) image = CloudinaryField('image') # Points to a Cloudinary image def __str__(self): return self.title I'm using serializer to grab endpoints in json via React with DjangoRESTframework but this shouldn't matter for now -
Autofill blank required fields in Django admin before save and before validation
I have a model 'Production' and a model 'Show'. 'Production' has a foreign key linking it to a specific show. In admin, the user has the option to fill out the title of the production. This is currently a required field. However, if the user leaves it blank I want to be able to fill it in automatically based on the title of the foreignkey Show. I have written a function that overrides save and makes this happen. However, it cannot run because if the user leaves the field blank, Django admin tells them "This field is required" before allowing the save function to run. How can I prevent this? I do not want to make the fields null=True,blank=True in the Model itself because I still want this field to always be filled. Code below (bits removed for clarity): @admin.register(Production) class ProductionAdmin(admin.ModelAdmin): inlines = [ RoleInLine, CreativeRoleInLine, ] def has_change_permission(self, request, obj=None): if request.user.is_superuser: return True if obj is not None and obj.lead_producer != request.user.profile.creative: return False return True def save_model(self, request, obj, form, change): if not obj.title: obj.title = obj.show.title + " - " + obj.theatre.city.name + " Production" obj.save() class Production(models.Model): """Model definition for MODELNAME.""" show = models.ForeignKey(Show, … -
Allowing a user to only be able to edit their own info with a custom model in Django error
I am new to development and Django. This is my first project from scratch. I decided to go with a custom user model so I could customize the registration page and require users to submit a photo during registration. I am making a tinder clone and I wanted to make sure users submitted a photo. However, as result of using a custom model, things have been more difficult. Right now, I am attempting to only allow the current logged in user to be able to edit their own info, not anyone else's. The only way I know how to do this is to create a separate model that has a foreign key to my Profile model, 'owner', and compare the two ID's when the current user try's to edit someone else's profile. However, I am having trouble adding that model to my custom model. Here is the error I am getting which I don't understand even though I tried looking it up...; django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: dating_app.Profile.owner: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. models.py from django.db import models from django.contrib.auth.models … -
Failure on git push, file not found /tmp/build/static
I am having trouble with a git push to update my Heroku app. At the end of the error log this is what comes up: remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, in collect remote: for path, storage in finder.list(self.ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 131, in list remote: for path in utils.get_files(storage, ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files remote: directories, files = storage.listdir(location) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 315, in listdir remote: for entry in os.scandir(path): remote: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_8e6aeb15085bd120f62a7e71199f0368/static' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. I have tried updating my gitignore, my settings static files location, and running git pull heroku master. The app works perfectly well on localhost. All help is appreciated! -
'ContactView' object has no attribute 'request'
Thanks for entertaining what is hopefully an easy fix. I have a website with a "Contact Us" page where the user can enter Name etc. and send a message. Along with this view, I collect the IP data and use MaxMind to store the geographic data of the user. I have a view that calls a function that grabs the IP and pings MaxMind to get the data. My view looks like this: class ContactView(CreateView): model = Contact template_name = "contact/contact.jinja" form_class = ContactForm success_url = "/" def __init__(self, *args, **kwargs): self.initial['ip_information'] = get_ip_data(self.request) #<< Call the IP function def form_valid(self, form): # Update Slack: first_name = form.data["first_name"] last_name = form.data["last_name"] email = form.data["email"] phone = form.data["phone"] ip_information = form.data["ip_information"] # << this is where the IP Data is stored [ ... ] return super().form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["service_list"] = Service.objects.all().order_by("rank") context["county_list"] = County.objects.all().order_by("county") return context The function being called, which requires a request object, looks like this: def get_ip_data(request): # Get IP information # MaxMind Database for geoIP client = geoip2.webservice.Client(#####, "XXXXXXXXXXXXXXXX") x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR") if x_forwarded_for: client_ip = x_forwarded_for.split(",")[0] else: client_ip = request.META.get("REMOTE_ADDR") ip_data = client.city(client_ip) return ip_data Unfortunately, ContactView(CreateView) does not seem to give … -
stripe-python, should it be async?
I need to integrate Stripe into a Django project and I noticed that there's a stripe-python package. This runs entirely synchronously though. Is it a bad idea to make these types of call from the main web server? Since it makes external calls, this presumably means the webserver will be blocked while we wait for a response, which seems bad. So, should I be running this from something like Celery? Or is it fine to run on the main thread? Anyone have experience with this? -
Performance Issue when saves request POST using modelformset_factory
I'm working on a project where i'm required to display 50 form per page related to specific model. I use modelformset_factory to display and edit multiple instance at once, but i faced a performance issue while saving around 50 records(50 form of same model). it makes more than 350 queries in order to save the data, I used django-debug-toolbar. to check the performance and unfortunately each record/form makes multiple queries. click to view the result from django-debug-toolbar here's snippet of the code: def offerScoring(request, offid, page): formset = modelformset_factory(Enroll, extra=0, form=Scoring) if request.POST: form = formset(data=request.POST) if form.is_valid(): form.save() messages.add_message(request, messages.INFO, "Scores are saved updated successfully") return redirect(reverse('offerScoring', kwargs={'offid': offid, 'page': page})) else: messages.add_message(request, messages.INFO, "Scores were NOT updated ") AllEnrolled = Enroll.objects.select_related('StudentID','OfferingID','OfferingID__Course').filter(OfferingID=offid) paginator = Paginator(AllEnrolled, 50) Enrolled = paginator.get_page(page) Enrolled.ordered = True if request.method == "GET": form = formset(queryset=Enrolled) return render(request, template_name='Course/templates/offerScoring.html', context={'form': form, 'Enrolled': Enrolled}) Any ideas on how to reduce the number of queries when the form is submitted? -
I need to sent clients catalog, after they left their email on site working on django+wagtail?
I think about something like this: crone start python script wich parse csv file with emails every 2 minutes. script take new email and with help of smtplib and gmail sent email with catalog What do you think about it or i can use something in django or wagtail? Any ideas please! -
Django: Group by through annotate is not working properly
i am building a simple todo app and i need to group them by status and status occurence. i tried using: instance = request.user instance.todos.values('status').annotate(counter=Count('status')) but i get this output: <QuerySet [{'status': 'ON-GO', 'counter': 1}, {'status': 'ON-GO', 'counter': 1}, {'status': 'ON-GO', 'counter': 1}, {'status': 'CHECK', 'counter': 1}, {'status': 'CHECK', 'counter': 1}]> i have used this method before and it gave me the results i need but now it just does not work. any workarounds ? -
How to fix ordered list sequence of database in Django?
I create a project that displays the first and last name of the user and email if users goes to the "/users". it is working fine but the issue is I am getting same number in the ordered list when I try to display the data. Kindly refer to the image for details. dj Here is the code for the HTML file... How do I fix this issue? <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>User Page</title> <link rel="stylesheet" href="{% static 'css/usercss.css' %}"/> </head> <body> <h2>Welcome to user page</h2> {% if accessdata %} <ol> {% for elements in accessdata %} <li>UserProfile</li> <ul> <li> {{ elements.firstname }}</li> <li> {{ elements.lastname }}</li> <li> {{ elements.email }}</li> </ul> {% endfor %} </ol> {% else %} <p> No users found</p> {% endif %} </body> </html> -
Redirecting after the conversion is done with Django
I have a website where the user uploads an mp4 and presses the button to convert it. What I need to do is to redirect to another page where he/she can play it. But I need to make sure the conversion is done before redirecting. How can I do this on the back-end side? Thanks in advance -
upload_to attribute returning wrong path
upload_to attribute isn't working correctly. I have no idea what's causing this, instead of uploading a file I'm getting a SuspiciousFileOperation exception. The base path component stated in the exception is correct but joined path is not correct as it should just be 'img/posts'. I'm looking for a reason that's causing this. models.py thumbnail = models.FileField(upload_to='img/posts') Exception value The joined path (/media/tb1.jpg) is located outside of the base path component (/home/user/Documents/project/project/media) -
Im using Django and in my views.py file line 11: user = form.save() is resulting in a UNIQUE constraint failed: auth_user.username error
I've looked at the questions asked and but I cant figure out what I'm missing. When I try to test my register page it throws the UNIQUE constraint failed. I know it has some relation to form.save() in my views. Another questions solution stated that they were attempting to save the form twice. I'm sure I'm not doing that but I could be wrong. Views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm, bUserRegisterForm, UserProfileForm from django.contrib.auth import authenticate, login, logout def studentreg(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form .is_valid(): form.save() first_name = form.cleaned_data.get('first_name') messages.success(request, f'account created for {first_name}!') return redirect ('/home/studentlogin.html') else: form = UserRegisterForm() #this will return an empty form return render(request, 'users/studentregisterform.html', {'form': form}) def getstarted(request): return render(request, 'home/getstarted.html') def chooseaccount(request): return render(request, 'home/chooseaccount.html') def businessreg(request): if request.method == 'POST': form = UserRegisterForm(request.POST) profile_form = UserProfileForm(request.POST) if form .is_valid () and profile_form.is_valid(): user = form.save() profile = profile_form.save(commit=False) profile.user = user profile.save() first_name = form.cleaned_data.get('first_name') messages.success(request, f'account created for {first_name}!') return redirect ('admin/') else: form = bUserRegisterForm() profile_form = UserProfileForm() return render(request, 'users/businessregisterform.html', {'form': form, 'profile_form' : profile_form}) def bloginpage(request): if request.method == 'POST': Email_Address = request.POST.get('Email_Address') password = … -
Django UpdateWithInlinesView not saving deleted inlines
I'm using a jQuery plugin (by elo80ka) for adding and deleting inlines from Template. The issue I have is when I'm adding new data all goes well and data gets saved. But once I try to remove existing ones I get a redirect without deleted objects. (once I hit remove, the inline gets removed, I've checked via Inspector) class PlaceUpdateInline(InlineFormSetFactory): model = AdditionalLoadingPlace form_class = AdditionalLoadingPlaceInlineFormSet factory_kwargs = {'extra': 0, 'max_num': 5, 'can_order': False, 'can_delete': True} class PlaceUpdateView(LoginRequiredMixin, UpdateWithInlinesView): model = Place form_class = PlaceCreateForm inlines = [PlaceUpdateInline] def forms_valid(self, form, inlines): form.instance.author = self.request.user self.object = form.save(commit=False) self.object.author = self.request.user form.save(commit=True) for inline in inlines: objects = inline.save(commit=False) for obj in inline.deleted_objects: # never called obj.delete() for object in objects: if object.place: object.save() return HttpResponseRedirect(self.get_success_url()) -
Django, UpdateView deletes a row in the table
i complete remade a script, because i thought, an additional component is deleting a row in my database, which it doesn't. My script somehow manages to do it: Here are the facts: The Model is called "Settings", which is implemented as a Singleton: class Setting(SingletonModel): page = models.IntegerField() profile = models.ForeignKey(Profile, on_delete=models.CASCADE, blank=True, null=True, default=None) addmonitored = models.BooleanField(default=True, verbose_name="Add shows as monitored to Sonnar") folders = models.BooleanField(default=True, verbose_name="Subfolders for seasons") def __str__(self): return "Settings" class Meta: verbose_name_plural = "Settings" The base Model looks like this: class SingletonModel(models.Model): class Meta: abstract = True def save(self, *args, **kwargs): self.pk = 1 super(SingletonModel, self).save(*args, **kwargs) def delete(self, *args, **kwargs): pass @classmethod def load(cls): obj, created = cls.objects.get_or_create(pk=1) return obj The FormView looks like this: class SettingsFormSetView(UpdateView): model = Setting exclude = ['page', 'xxxxxx'] template_name = 'settings.html' def get_object(self): return Setting.objects.get(pk=1) def get_success_url(self): return reverse('settings') I can open the form without any problems, enter the data, save it. I can reload the page and it still shows the data. If i reload it a few times, suddenly the form is empty and the row (pk=1, which is the only row in that table) is also deleted from the database. No other stuff is interfering … -
Using postgres bigserial as autoincrement id field and pk with a more recent version of django
I want to be able to use the bigserial data type for the pk of my django model. I do not want to do it manually with each model i create. Is there any way to change django to use bigserial instead of the serial datatype? All the searches i have done result in having to change the database for each model or a workaround but with an earlier version of django in like the 1.x version. Is there a more recent or better way to do this? -
Django trying to add upload directory for images (E004)
So my current goal is to be able to allow admins to upload images such as thumbnails in certain models . So I started off by creating a folder called uploads in the projects root directory. In my models.py I'm using thumbnail = models.ImageField(name="photo", upload_to='uploads/thumbnails/', null=True, default='default.png') which successfully uploads files to that directory. The problem though is accessing those files once they're uploaded. I edited my urls.py to look like this from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.urls import path from . import views app_name = 'blog' urlpatterns = [ #... static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT), ] and I added the following to my settings.py AUTH_USER_MODEL = "blog.User" MEDIA_URL = "/uploads/" MEDIA_ROOT = os.path.join(BASE_DIR, "uploads") Now I keep getting the following error: django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (urls.E004) Your URL pattern [<URLPattern '^uploads/(?P<path>.*)$'>] is invalid. Ensure that urlpatterns is a list of pa th() and/or re_path() instances. I'm fairly new to django so if this question can be improved by all means let me know. -
How can I configure VS Code to work with Prettier HTML formatter?
I am trying to have VS Code format my Django HTML files but I am getting: There is no document formatter for 'django-html'-files installed. The solution I found on the web works with Beautify, not Prettier. How can I make it work with Prettier? -
Django - How can I get form data to my view that handles my ajax calls when the form is rendered in a different view for the same template
I have a form rendered to a page from this view: def foo(request): form = MyForm() return render(request, template_name=template, context={'form': form}) From a different view I handle my ajax calls which loads data from a url to the same template as the view above. I need to use the input from that form to reload the page using Ajax with the filtered results. How can I gain access to the form from my Ajax view? class AjaxView(APIView): authentication_classes = [] permission_classes = [] def get(self, request): form_data = request.GET.get # Need to get form submission data here def handle_new_page_logic(form_data) ... return Response() -
Your requirements.txt is invalid. AWS Elastic Beanstalk, Django
i am new to aws and django. I was tryinh to upload my code to aws elastic beanstalk using code commit while i am getting the folowing error please suggest what to do 2020/03/12 13:42:30.200017 [ERROR] Command timed out after 300 seconds 2020/03/12 13:42:30.202535 [ERROR] Command /bin/sh [-c python3 -m pipenv install -r requirements.txt --skip-lock] failed with error signal: killed 2020/03/12 13:42:30.204812 [ERROR] An error occurred during execution of command [app-deploy] - [SetUpPythonEnvironment]. Stop running the command. Error: fail to install dependencies with requirements.txt file with error Command /bin/sh [-c python3 -m pipenv install -r requirements.txt --skip-lock] failed with error signal: killed 2020/03/12 13:42:30.204825 [INFO] Executing cleanup logic 2020/03/12 13:42:30.210383 [INFO] CommandService Response: {"status":"FAILURE","api_version":"1.0","results":[{"status":"FAILURE","msg":"Engine execution has encountered an error.","returncode":1,"events":[]}]} 2020/03/12 13:42:30.211588 [INFO] Platform Engine finished execution on command: app-deploy -
Showing a date range from a set of date objects
I have a two set of dates: Set #1: 1805 Nov. 11 1805 Nov. 12 1805 Nov. 13 Set #2: 1805 Nov. 11 1805 Nov. 13 1805 Nov. 14 What is the easiest way to display a date range. For Set #1: I expect to show: 1805 Nov. 11-13 For Set #2, I want to show: 1805 Nov. 11, 13-14