Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How do I run a function on each post in my list view and pass a boolean variable into my html?
My html {% if is_liked %} <i class="fa fa-check" aria-hidden="true"></i> {% else %} <i class="fa fa-times" aria-hidden="true"></i> {% endif %} My views.py class PostListView(ListView): queryset = Post.objects.filter(created__range=['2020-03-01', '2020-03-31']) template_name = 'main/problems.html' context_object_name = 'posts' ordering = ['-created'] for post in queryset: def get_liked(self): if self.likes.filter(id=self.request.user.id).exists(): is_liked = True else: is_liked = False return is_liked Even if I set both conditionals to return true my html does not read is_liked as true. -
CORS Policy Issue Between React and Django App
I got this issue when trying to get data in my React app from my Django app: Access to XMLHttpRequest at 'https://quiet-retreat-95482.herokuapp.com/api/todos/' from origin 'https://infallible-jackson-111720.netlify.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I made a React todo list app and deployed it here: https://infallible-jackson-111720.netlify.com/ I made my Django backend and deployed it on Heroku: https://quiet-retreat-95482.herokuapp.com/ In my backend code, I think I installed and have the correct settings for corsheader: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'todo' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = [ 'https://infallible-jackson-111720.netlify.com' ] import django_heroku django_heroku.settings(locals()) I also had requirements.txt and Procfile for heroku and the app was deployed successfully. I was able to get data locally when my backend was running on my localhost: http://127.0.0.1:8000/api/todos/ What was the cause of this error and how can I fix it? If need any other information, please let me know. Thank you a lot! -
Iterate over several querysets in django template with nested loop
I am making a hotell-page, and have made models for bookings and rooms. I want to display the bookings related to a room in a table, and have the related bookings laying under the spesific room. I show the code from the views.py file here: def vaskehjelp(response): available_rooms = Room.objects.filter(available=True) room_nums = [] context = {} for room in available_rooms: related_bookings = Booking.objects.filter(room=room) if related_bookings: room_nums.append(room.room_no) context[room.room_no] = related_bookings context["room_nums"] = room_nums context["available_rooms"] = available_rooms print(context) return render(response, "../templates/se_vaskbare_rom.html", context) and the code from my template file here: <table class="table table-striped table-dark"> <tr class="thead-dark"> <th scope="col">Room No.</th> <th scope="col">Capacity</th> <th scope="col">Room Type</th> </tr> {% for item in available_rooms %} <tr scope="row"> <td>{{ item.room_no }}</td> <td>{{ item.capacity }}</td> <td>{{ item.room_type }}</td> </tr> {% if item.room_no in room_nums %} {% for booking in item.room_no %} <h1></h1> <tr scope="row"> <td>{{ booking.cin_date }}</td> <td>ku</td> <td>{{ booking.cout_date }}</td> </tr> {% endfor %} {% endif %} {% endfor %} </table> The problem is that the booking-element in the template code doesent seem to work. I dont manage to access the lists of bookings related to the current selected room. As you see i have an outer for loop to iterate over the rooms, and then the … -
psycopg2.errors.UndefinedColumn: column ... does not exist
Hello I am trying to migrate an app 'projects'. On my local machine, I had made many changes to the model over time and so I have many different migrations for the app. When I am trying to migrate to my web server, I receive an error on the fourth migration file. Error: Applying projects.0001_initial... OK Applying projects.0002_auto_20200227_1959... OK Applying projects.0003_project_garage... OK Applying projects.0004_auto_20200301_2331...Traceback (most recent call last): File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column projects_project.accessible_to_foreigners does not exist LINE 1: ...opertytype2", "projects_project"."propertytype3", "projects_... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 233, in handle fake_initial=fake_initial, File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state … -
Python django model validate min and max value
I want to limit the title to between 3 and 25 characters. I could not get MinLengthValidator to work. I'm new to Python. class Video(models.Model): title = models.CharField(max_length=255) url = models.URLField() youtube_id = models.CharField(max_length=255) def clean_title_length(self): data = self.cleaned_data['title'] length= len(data) if length < 3 or length > 25: raise ValidationError("The length of the title must be between 3 and 25 characters") else: return data views.py def add_video(request): form = VideoForm() if request.method == 'POST': filled_form = VideoForm(request.POST) if filled_form.is_valid(): The above form always returns valid. Suggestion on how I can get this range validator to work? TIA -
Django admin for User changes Groups widget when I add a custom admin
I want to use the out-of-the-box User model in Django, but add an action to the admin. Without any custom admin, the User's admin has this many-to-many control for groups: But when I register a custom Admin: class CustomModelAdmin(admin.ModelAdmin): actions = ['custom_action'] def custom_action(self, request, queryset): pass custom_action.short_description = "Custom Action" admin.site.unregister(User) admin.site.register(User, CustomModelAdmin) The control changes to a simpler select. I want the original one, as my list of groups may get large. Why did it change? How do restore it to the former? -
How to get a model's last access date in Django?
I'm building a Django application, and in it I would like to track whenever a particular model was last accessed. I'm opting for this in order to build a user activity history. I know Django provides auto_now and auto_now_add, but these do not do what I want them to do. The latter tracks when a model was created, and the former tracks when it was last modified, which is different from when it was last accessed, mind you. I've tried adding another datetime field to my model's specification: accessed_on = models.DateTimeField() Then I try to update the model's access manually by calling the following after each access: model.accessed_on = datetime.utcnow() model.save() But it still won't work. I've gone through the django documentation for an answer, but couldn't find one. Help would be much appreciated.