Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get previous page url in django template?
i am using the django password reset but i want my template to behave differently when it come from password_rest_email and from password_reset_confirm urls.py from django.conf.urls import url,include #from django.urls import path from dappx import views from django.contrib.auth.views import PasswordResetView,PasswordResetDoneView,PasswordResetCompleteView,PasswordResetConfirmView # SET THE NAMESPACE! app_name = 'dappx' # Be careful setting the name to just /login use userlogin instead! urlpatterns=[ url('register/', views.register, name='register'), url('user_login/', views.user_login, name='user_login'), url('google_login/', views.google_login, name='google_login'), url('special/', views.special, name='special'), url('logout/', views.user_logout, name='logout'), url(r'^', include('django.contrib.auth.urls')), url('password_reset/', PasswordResetView.as_view(), name='password_reset'), url('password_reset/done/', PasswordResetDoneView.as_view(), name='password_reset_done'), url('reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), ] i need that template i.e(password_reset_confirm) to show email is send when it come from password_reset_email and show password reset successful if it come from password_reset_confirm password_reset_complete.html {% extends 'dappx/base.html' %} {% block title %}Check your Email{% endblock %} {% block body_block %} <div class="row no-gutters"> <div class="col-12 col-sm-6 col-md-8"></div> <div class="col-6 col-md-4"> <div class="jumbotron"> <h4>The password reset link has been sent to youre Email</h4> <br> <p>Check your email to reset the password. You can log in now on the <a href="{% url 'dappx:user_login' %}">log in page</a>.</p> <br> </div> </div> {% endblock %} -
Django Data to JsonResponse
I have this model that store all my data. This is my model.py: from django.db import models class Showing(models.Model): movie_id = models.CharField(primary_key=True, max_length=11) movie_title = models.CharField(max_length=100) image_url = models.TextField(blank=True) synopsis = models.TextField(blank=True) rating = models.TextField(default="MTRCB rating not yet available") cast = models.CharField(max_length=100) release_date = models.CharField(max_length=50, blank=True) def __str__(self): return "{}".format(self.movie_id) And I want to retrieve all my data and pass it to context and make a customize JsonResponse like this: "results": [ { "id": "1eb7758d-b950-4198-91b7-1b0ad0d81054", "movie": { "advisory_rating": "PG", "canonical_title": "ROGUE ONE: A STAR WARS STORY", "cast": [ "Felicity Jones", "Donnie Yen", "Mads Mikkelsen" ], "poster_portrait": "", "release_date": "", "synopsis": "Set shortly before the events of Star Wars (1977), Following the foundation of the Galactic Empire, the story will center on a wayward band of Rebel fighters which comes together to carry out a desperate mission: to steal the plans for the Death Star before it can be used to enforce the Emperor's rule. (Source: Disney Pictures)", } }, ] In my views.py I have this function to get all the data, and try just to retrive the movie_id from my model. def show_all_movies(request): movie = Showing.objects.all() context={'result':[{ 'id':movie.movie_id, 'movie': }]} But it gets me an error of 'QuerySet' object … -
how to send pre_save signal only when hit the save button for multiple form in one view (formset)
i trying to send signal only when the user hit the button save class Product(models.Model): name = models.CharField(max_length=50) price = models.PositiveIntegerField(default=1) def __str__(self): return self.name class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') @property def total(self): return self.productorder_set.aggregate( price_sum=Sum(F('quantity') * F('product__price'), output_field=IntegerField()) )['price_sum'] class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE,default='' ) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) @receiver(pre_save , sender=ProductOrder) def create_order(sender, instance, **kwargs): Order.objects.create() if not instance.ordering: instance.ordering = Order.objects.all().order_by('-pk')[0] pre_save.connect(create_order,sender=ProductOrder) forms.py class ProductOrdering(forms.ModelForm): class Meta: model = ProductOrder fields = ['product','ordering','quantity'] ProductFormSet = formset_factory(ProductOrdering , extra=2) i want to make only one id from Order for all forms in the same view , while hit the button ? thanks for advice -
ModelForm add the primary ID for an entry in table based on last entry's primary ID
I am creating a signup system. I am using the django's default User's model to store user details, and I am passing its objects into a model named "Employee" where their department, manager and other info is stored. Here is what I have. models.py: from django.contrib.auth.models import User class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user') .... forms.py: from users.models import Employee from django.contrib.auth.models import User from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm class AddNewUserForm(UserCreationForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') class AddNewEmployeeForm(ModelForm): class Meta: model = Employee fields = {'department', 'manager', 'total_leaves'} add_new_user.html: <form method="POST"> {% csrf_token %} {{ form_user.as_p }} {{ form_emp.as_p }} <div class="text-center"> <button type="submit" class="btn btn-success">Submit</button> </div> </form> And this is how I'm processing the data in views.py: def post(self, request): form_user = AddNewUserForm(request.POST) form_emp = AddNewEmployeeForm(request.POST) if form_user.is_valid(): emp_info = form_emp.save(commit=False) emp_info.leaves_taken = 0 emp_info.user = form_user.save() emp_info.save() messages.success(request, "Success!") else: messages.error(request, form_user.errors) messages.error(request, form_emp.errors) return redirect("add_new_user") The problem is that when the post method is run, it tries to add entries into Employee table from the beginning; assuming there are no entries in it. But I have entries in that table and I get the following … -
How can i save some data in Django without adding it in the form?
I have a model which looks like this: class MyModel(models.Model): rate = models.CharField(max_length=100) amount = models.FloatField() userid = models.CharField(max_length=100) def save(self): # ALL the signature super(MyModel, self).save() And a form: class MyForm(forms.ModelForm): rate = forms.CharField() amount = forms.FloatField() class Meta: model = MyModel fields = ("rate", "amount") def save(self, commit=True): send = super(MyForm, self).save(commit=False) if commit: send.save() return send At the actual moment, my form is saving the fields rate and amount on my database, once the user uses the form. I would like to save on my DB the user who submitted the form, the date/time of when the form was saved and some other data that must not be submitted by the user, but saved 'automatically'. How can i do that in Django? -
How to generate a user password in plain SQL with Django + PostgreSQL
I want to insert from a Django into another Django database from other domain a proper password text in auth_user table. I have tried to generate a encrypt function but I don't know how Django generates a password from plain text into hashed password that is stored in database. postgres_insert_query = """ INSERT INTO auth_user (username, first_name, last_name, email, password) VALUES (%s,%s,%s,%s,%s) """ record_to_insert = (username, first_name, last_name, email, password) cursor.execute(postgres_insert_query, record_to_insert) connection.commit() cursor.close() -
Django not serving static on digital ocean ubuntu 18.04
I have just successfully uploaded and run my project on digital ocean. It has been developed before production according to the coreyMS tutorials on youtube with the latest version of django 2.1.7. It has been deployed with this tutorial on ubuntu 18.04 on a digital ocean droplet. I cant make it serve any static files. The structure of my project is: newsite/myforum/ in here is the manage.py In the newsite/myforum/myforum/ is the settings.py and i have 3 apps users, forum and store that are all in folders in the newsite/myforum directory. The static folder according to the coreyms tutorial for the latest django version is supposed to be in my main app, therefore forum/static/forum. So the total path is newsite/myforum/forum/static/forum My settings are: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' In the nginx configuration i have specified the path, home/myuser/mydir/myenv/newsite/myforum maybe i should try: home/myuser/mydir/myenv/newsite/myforum/forum/static/forum or just: home/myuser/mydir/myenv/newsite/myforum/forum/static/ Or should i change my django settings and then run a collectstatic command. It took me a long time to get this far with the deployment and i dont want to run a stupid command and ruin it. Thank a lot for the help!!!!!!!!!! -
Generict django content type , get the object stored in contentype
Well similar questions have been asked, but none of the answers works for me . Bellow is my contentype model class notifyall(models.Model): target_instance=models.ForeignKey(ContentType,null=True,on_delete=models.CASCADE,blank=True) object_id=models.PositiveIntegerField(null=True) target_object=GenericForeignKey('target_instance', 'object_id') As you can see, contentype has a GenericForeignKey to store different kind of objects from different models when notifyall object is created , this is what i will get >>object_id= e.g 20 >>target_instance = class_name_of_model what is the right way to go about retrieving the object stored in contentype model as object_id and target_instance -
Circular import error when importing weasyprint's HTML
I am trying to generate a pdf and I am getting the error below. raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'tenderwiz.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. The error occurs when I include this line in my view from weasyprint import HTML utils.py from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from django.conf import settings import os from django.template.loader import render_to_string from weasyprint import HTML def render_to_pdf(template_src, context_dict={}): html_template = render_to_string('invoice_render.html', context_dict) pdf_file = HTML(string=html_template).write_pdf() response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = 'filename="invoice.pdf"' return response user_accounts/views.py from .utils import render_to_pdf from django.shortcuts import render, render_to_response, redirect, get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.contrib import auth from django.template.context_processors import csrf from packages.models import Packages from .forms import (CustomUserForm, CompanyProfileForm, CompanyProfileEditForm, BankingDetailsForm, PayFast_Form, ) from django.contrib.auth import update_session_auth_hash from .models import CompanyProfile, OurDetails from django.contrib.auth.models import User from django.contrib.auth.forms import PasswordChangeForm, PasswordResetForm from tender_details.models import Category, Keywords, Province from django.core import serializers from django.http import HttpResponse from django.contrib import messages from django.urls import reverse import json from urllib.parse import urlencode, quote_plus import hashlib from django.conf import settings … -
How to test django channel layer with virtual-env on windows 10?
I'm using anaconda to make virtual environment and using it to develop my django apps. Now I'm working on a project that needs to use websocket to send notifications. I followed this Tutorial and first part worked well but this second part needs to open a port on computer to send data between users, using channel_redis and redis on docker to do this stuff, but as I said I'm using virtual-en on my local system. so is there a way to make it happen? The Output: raise OSError(err, 'Connect call failed %s' % (address,)) ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 6379) Sorry for bad english 😓 -
TypeError: 'ShiftSerializer' object is not callable
I am trying to do with ModelViewSet. I am facing this error now Here is my viewset=> class ShiftViewSet(viewsets.ModelViewSet): queryset = Shift.objects.all() serializer_class = ShiftSerializer() # filter_backends = (filters.DjangoFilterBackend,) # filterset_fields = ('shiftid',) @action(methods=['get'], detail=False) def newest(self, request): newest = self.get_queryset().order_by('Created_DT').last() serializer = self.get_serializer_class()(newest) return Response(serializer.data) @action(methods=['get'], detail=False) def shiftsum(self, request): query = ( Shift.objects.values('shiftid') .annotate(shiftdesc=Max('shiftdesc')) .annotate(overnight=Max('overnight')) .annotate(isspecialshift=Max('isspecialshift')) .annotate(ct=Count('*')) # get count of rows in group .order_by('shiftid') .distinct() ) serializer = ShiftSummarySerializer(query,many=True) return Response(serializer.data) @action(methods=['get'], detail=False) def byshiftid(self, request): shiftid = self.request.query_params.get('shiftid',None) query = self.get_queryset().filter(shiftid=shiftid) serializer = ShiftSerializer(query,many=True) return Response(serializer.data) Here is my router and url => router.register('shifts_mas', ShiftViewSet, base_name='shifts') path('api/', include(router.urls)) Normally I can call like /api/shifts_mas/ and I will get all record of shift but just now i got this error and i dont know why. May i know why? -
pip inside virtual environment is pointing to global installation and doesnt use the virtualenv site packages
I have a local repo where I have installed packages like django, django rest framework with virtual environment, I have pushed it to git and when I have downloaded the repo on a remote server, I have activated the virtualenv using source bin/activate and tried to run django server, it is showing the packages which are installed inside the virtualenv as not installed I have tried to use which python3.5 It gives me /usr/bin/python3.5 And which pip3 gives /usr/local/bin/pip3, what do I need to make the virtualenv to use the packages inside virtual env lib/ folder? I have no aliases set on bashrc, any idea why this is happening? -
Deploying Django site to heroku isn't working
Me and @MD-Khairul-Basar have been talking for a great while on this chat trying to figure out why my site isn't deploying to heroku. I've tried everything that he's suggested but none have worked. I've put my code on Github so you can see it. The recent errors (HTTP 500) seen on the chat are still the most recent on my local computer. Please help :) dj-database-url==0.5.0 Django==2.2.3 django-crispy-forms==1.7.2 gunicorn==19.9.0 Pillow==6.1.0 psycopg2==2.8.3 pytz==2019.1 sqlparse==0.3.0 whitenoise==4.1.3 python==3.7.3 -
What should I modify to add a new field in django-rest-framework?
I want to make "channel" available in the next html form. But I don't know how. Can you help me? models.py class Channel(models.Model): name = models.CharField(_('Name'), max_length=100) # 1(User 진행자) : N(Channel) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='vod_owner_channels', verbose_name=_('User')) description = models.TextField(_('Description'), max_length=1000, blank=True) background_image = models.ImageField(_('Background Image'), upload_to='background_image/%Y/%m/%d', blank=True) create_date = models.DateTimeField(_('Channel Create Date'), auto_now_add=True) class Video(models.Model): # 1(Channel) : N(Video) channel = models.ForeignKey(Channel, on_delete=models.CASCADE, related_name='vod_channel_videos', verbose_name=_('Channel')) title = models.CharField(_('Title'), max_length=100) description = models.TextField(_('Description'), max_length=1000, blank=True) video = models.FileField(_('Video'), upload_to='video/%Y/%m/%d', blank=True) video_url = models.URLField(_('Video URL'), blank=True) views = models.PositiveIntegerField(_('Views'), default=0) create_date = models.DateTimeField(_('Create Date'), auto_now_add=True) update_date = models.DateTimeField(_('Update date'), auto_now=True) class Comment(models.Model): # 1(User) : N(Comment) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='vod_user_comments', verbose_name=_('Comment')) # 1(Video) : N(Comment) video = models.ForeignKey(Video, on_delete=models.CASCADE, related_name='vod_video_comments', verbose_name=_('Video')) content = models.TextField(_('Content'), max_length=1000) create_date = models.DateTimeField(_('Create Date'), auto_now_add=True) update_date = models.DateTimeField(_('Update date'), auto_now=True) reply = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE, related_name='vod_reply_comments', verbose_name=_('Reply')) class Meta: verbose_name = _('Comment') verbose_name_plural = _('Comments') serializers.py class VideoSerializer(serializers.ModelSerializer): channel = serializers.ReadOnlyField(source='channel.name') class Meta: model = Video fields = ['id', 'channel', 'title', 'description', 'video', 'video_url', 'views', 'create_date', 'update_date'] I tried to make serializers.PrimaryRelatedKey. But it didn't work. I think, I can solve this problem in this code. but I don't have confidence. views.py # … -
How can I answer to shell questions
I am trying to create a simple program to create a superuser for django but I can't answer to the questions after that. os.popen('python manage.py createsuperuser') when this line of code runs, the interpreter asks me to enter a username like the picture in below : How can I answer that using some variables in python codes and not by hand. I want the program to handle it not a human. Also I can't really work with the manage.py file because then I have to change the content in the library which is not good. -
ModelForm in Django
ModelForm: def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(ChapterCreateForm, self).__init__(*args, **kwargs) Not working I wana add self.field other. But it not working. -
Parsing static json file and save values to Django Database/model
I have json file in my static folder in my django project. And I want to save the data from json file to my Django Database. This is my model.py from django.db import models class Coming_Soon(models.Model): movie_id = models.CharField(primary_key=True, max_length=11) movie_title = models.TextField(blank=True,max_length=100) image_url = models.TextField(blank=True) synopsis = models.TextField(blank=True) rating = models.TextField(default="MTRCB rating not yet available") cast = models.TextField(blank=True) release_date = models.TextField() this is sample of my json file { "results": [ { "rating": "PG", "cast": [ "Jeremy Ray Taylor", "Gerard Butler", "Abbie Cornish" ], "synopsis": "some synopsis", "movie_title": "(3D/4DX) GEOSTORM", "image_url": "some url", "id": "8595" }, { "rating": "PG", "cast": [ "Jeremy Ray Taylor", "Gerard Butler", "Abbie Cornish" ], "synopsis": "some synopsis", "movie_title": "(ATMOS) GEOSTORM", "image_url": "some url", "id": "8604" }, what should I write on my view so that I can save those data into my django database? This is my views.py: def polls(request): ROOT_FILE = STATIC_ROOT + '/polls/coming_soon.json' json_data = open(ROOT_FILE) json_load = json.load(json_data) with open(ROOT_FILE, 'r') as data: parsed_json = json.load(data) for result in parsed_json['results']: # movie_id = [] # movie_id.append(result['id']) # join = " ".join(movie_id) return HttpResponse(result['results']['id']) I really don't have any idea about getting those file into my database. Thank you. -
How to upload files to databse using django in binary field?
I want to create a biometric authentication system, so i need to save bimetric data(thumb image) to database in binary form. How to do same using django? -
Get current user inside customer user creation form while saving
I have a form derived from UserCreationForm. When I create a member as an admin, on behalf of the member, I want to access the current user (admin), check few conditions, modify the new user object and then save. But self.request throws object has no attribute 'request' exception. Tried if self.request.user.is_superuser: inside save method of MemberCreationForm(UserCreationForm): CBV. class MemberCreationForm(UserCreationForm): def save(self, commit=True): record = super(MemberCreationForm, self).save(commit=False) if self.request.user.is_superuser: record.website_role = 3 record.is_staff=True want to get the current user (logged in user) before saving so that I can modify the new object and save according to the logged in users role. -
How can I loop through json file and return it as HttpRespones in Django?
I have a json file inside my static folder in my django project. I want to return on all the 'id', and 'title' of each data. I have this data in my json file. {"results": [ {"id": "1", "movie_title": "COCO","cast":["cast1","cast2"]}, {"id": "2", "movie_title": "THOR","cast":["cast1","cast2"]}, {"id": "3", "movie_title": "IRONMAN","cast":["cast1","cast2"]}]} I have this code that return all data from json file. def polls(request): ROOT_FILE = STATIC_ROOT + '/polls/coming_soon.json' json_data = open(ROOT_FILE) json_load = json.load(json_data) return HttpResponse(json.dumps(json_load)) I would like to get, for example, only some specific values like 'id', 'title'. But when I tried to foreach the results from json_load, It only returns the value of first item in file. Here's my code to that. for r in json_load['results']: return HttpResponse(r['id'] + r['movie_title') But this code only return the first data. Thank you. -
Shopping Cart for Django 1.11.7
I'ved developed my webapp using Django==1.11.7. Before 2.x came about. I would like to now add shopping cart into my application. What would be the recommended library to do this ? Thanks. -
Django with Huey task consumer: TestCase methods touch real DB
I'm writing a Django application employing the Huey task queue, configured as described in the relevant Huey docs. Running some basic tests, I disabled the immediate setting to try the manage.py run_huey command to run the task consumer in its own process. I then ran a Django TestCase that invokes a Huey task that writes to the database (which, inside a TestCase, should be a temporary database created for and destroyed after testing.) The task was consumed in the Huey process and functioned as expected; however, the object created in the task run by the test was written to my actual (development) database. I understand why -- whatever magic Django does to spin up a fake database when running tests just doesn't reach across to the Huey consumer process; and I understand that per the Huey docs, its default behavior is to run in immediate mode (executing tasks as soon as they are enqueued without running a scheduling database or a separate consumer process) when Django's DEBUG setting is enabled, so I was stepping out on a limb. However, I feel like I some of the standard Huey features that aren't available in immediate mode -- scheduling tasks to occur … -
IntegrityError Primary Key Invalid
Sorry I am still trying to learn, but can't get past this problem. I am following sentdex's tutorials for django web development, however I have hit a wall - the error shows "django.db.utils.IntegrityError: The row in table 'main_tutorial' with primary key '1' has an invalid foreign key: main_tutorial.tutorial_series_id contains a value '1' that does not have a corresponding value in main_tutorialseries.id." I've tried removing default=1, and on_delete=models.SET_DEFAULT/CASCADE. I've also tried deleting the SQL database, migrations. I've tried using SQ Browser for SQlite to try and change things. Sadly I've spent hours staring at this and trying to find an answer, any help would be greatly appreciated. Thanks! The code is : from django.db import models from datetime import datetime class TutorialCategory(models.Model): tutorial_category = models.CharField(max_length=200) category_summary = models.CharField(max_length=200) category_slug = models.CharField(max_length=200, default=1) class Meta: # Gives the proper plural name for admin verbose_name_plural = "Categories" def __str__(self): return self.tutorial_category class TutorialSeries(models.Model): tutorial_series = models.CharField(max_length=200, default=1) tutorial_category = models.ForeignKey(TutorialCategory, default=1, verbose_name="Category", on_delete=models.SET_DEFAULT) series_summary = models.CharField(max_length=200) class Meta: # otherwise we get "Tutorial Seriess in admin" verbose_name_plural = "Series" def __str__(self): return self.tutorial_series class Tutorial(models.Model): tutorial_title = models.CharField(max_length=200) tutorial_content = models.TextField() tutorial_published = models.DateTimeField('date published') tutorial_series = models.ForeignKey(TutorialSeries, default=1, verbose_name="Series", on_delete=models.SET_DEFAULT) tutorial_slug = … -
Saleor - Trying to modify the dashboard (add 'Job Title' to 'Customer' / 'Account')
I'm new here :) I'm trying to build an eCommerce site using Saleor as the framework, I'm having trouble understanding the framework with the intention to modify the admin dashboard and database. To start simple and practice, I'm trying to add a 'Job Title' field to customers, and want this to be editable on the dashboard. Currently, I've performed a django migration and the new field is liked up to the database - I modified /saleor/saleor/account/modles.py class User(PermissionsMixin, AbstractBaseUser): ... job_title = models.CharField(max_length=256, blank=True) PostgreSQL also works fine SELECT * FROM account_user; SQL Output Where I'm completely stuck is actually getting this field to work with the dashboard/ appear. I've gone through editing the files where 'First Name' field appears, as the django /templates/ file seems to reference a 'form' I can only assume is run by ReactJS (which I'm not as familiar with as Python). The files I've modified (and effectively copied what existed for 'First Name') are: added jobTitle: formData.jobTitle, to line 111 on static/dashboard-next/customers/views/CustomerDetails.tsx added block from line 128 on static/customers/components/CustomerDetails/CustomerDetails.tsx added block from line 24 and 61 on static/customers/components/CustomerDetailsPage/CustomerDetailsPage.tsx I'd really appreciate if someone can help point me in the right direction of how saleor / … -
How to include concurrent function in django app?
I'm building a web site with payments which works the following way: User gotta transfer money with some randomly generated comment, while I regularly check if payment was done and in case of success do something. I have function check_payments that check if payment was done and do stuff if so and I wanna run it every 2 minutes concurrently with my site. This function should have access to all models of my web app. How should I do it?