Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: how to get Foreign key id?
I have 2 models as below class Product(models.Model): product_name = models.CharField(max_length=100) product_weight = models.CharField(max_length=30) class ProductImage(models.Model): product = ForeignKey(Product, on_delete=models.DO_NOTHING) How to extract product_id in ProductImage model? Thanks in advance. -
Auto save login user_id as a foreignkey using forrm.py in django
how to submit form which automatically take user_id of current active user as a Foreignkey with form.py file in django -
Django Template format date string
I have date fields in my content dictionary in ISO format ('Y-m-d') and want to display these fields using the "date" filter of Django Template but whenever I use the date filter the date is not displayed and without the date filter it is displayed. As per the documentation, the "date" filter requires datetime object for filtering. Is there any work around to apply the filter apart from changing the content before sending it to the template? -
name 'login' is not defined. python (django)
I have one problem, w want create user and after login. i create user but can't login. my error ---> name 'login' is not defined. from django.contrib.auth.views import login. I tried this too but it didn't work where do I have a problem and how can it be resolved? i couldn't find a way to solve the problem on Google. please help me, Thanks in advance. views.py from django.shortcuts import render from django.http import HttpResponse import datetime from django.contrib.auth import authenticate from home.forms import SignUp def regform(request): if request.method == 'POST': form = SignUp(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password1') user = authenticate(email=email, password=raw_password) login(request, user) return redirect('home') else: form = SignUp() return render(request, 'home/home.html', {'form': form}) models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ from django import forms class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and … -
Multiple db constraints in Django model not working
I'm having issues getting multiple constraints to work (in postgres, if it matters). Here is the Meta: class Meta: constraints = [ CheckConstraint( check=(Q(target_value__gt=0) & ~Q(target_metric=DEFAULT)) | (Q(enabled=False) | Q(status=IMPORTING) | Q(status=IMPORT_FAILURE)), name="positive_target_value", ) ] It would seem straightforward enough to me, but it ends up not working. Here is the generated SQL (pulled from the db itself): target_value > 0.0::double precision AND NOT target_metric::text = 'DEFAULT'::text OR enabled = false OR status = 20 OR status = 30 And here is proof that it should actually work (pulled from a django console, where the conditions are copied from the migration file): Folder.objects.filter(models.Q(models.Q(('target_value__gt', 0), models.Q(_negated=True, target_metric='DEFAULT')), ('enabled', False), ('status', 20), ('status', 30), _connector='OR')) web_1 | Out[5]: <QuerySet [<Folder: aDifferentFolder>]> Folder.objects.filter(models.Q(models.Q(('target_value__gt', 0), models.Q(_negated=True, target_metric='**SOMETHING DIFFERENT**')), ('enabled', False), ('status', 20), ('status', 30), _connector='OR')) web_1 | Out[7]: <QuerySet [< Folder: Folder aDifferentFolder >, < Folder: Folder thisFolderShouldNotHaveBeenCreted>]> Anybody has any suggestion? Btw, I also tried switching the first condition with the second one, effectively putting the AND at the bottom of the query, but it didn't seem to have any effect. Thanks a lot. -
Displaying email address during sign up process in django-allauth's verification_sent template
Using django 2.2.9, django-allauth 0.39.1, I am trying to optimize the sign-up procedure. In the sign-up form, the user is asked to enter the email address 1x and the password 2x. Although this is fine, some users still mistype their email address and therefore never receive the verification email. As a solution, I thought one could maybe customize the message in the verification_sent.html template. I created a new template, which is working fine. Now, I'd like to add to the text the email address the user entered in the previous step in the sign-up form. That way the user would be able to see the email address once again and repeat the sign-up process if they spot a typo. Does someone know if there is a way to do this? -
ModuleNotFoundError: No module named 'allauth' when trying to createsuperuser
So, im new to Django and for the sake of learning im trying to get a project up with allauth while extending AbstractBaseUser. The project starts, there is no problem there, the login screen from allauth displays my custom model (login with email). But when i try to create a superuser i get the following error. 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 "C:\users\bramv\appdata\local\programs\python\python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\users\bramv\appdata\local\programs\python\python38\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\users\bramv\appdata\local\programs\python\python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\users\bramv\appdata\local\programs\python\python38\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\users\bramv\appdata\local\programs\python\python38\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\users\bramv\appdata\local\programs\python\python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'allauth' I did setup a virtualenv and installed django-allauth with pip and i followed the install instructions from the django-allauth docs. I fail to see where this error is comming from, any help would be greatly appreciated. -
How to fix Key Error when testing django create CBV?
I have been troubleshooting this problem for 3 days now. I think I'm missing something fundamental about testing Create Views or using client.post(). The test is failing because the date key is not present in the cleaned_data dictionary of the form, however, the code works correctly when executed from the browser. Can you please tell me why is the date key present in the cleaned_data dictionary when running in the browser but absent when executed by client.post() in the test? Below are snippets of relevant code. Models.py class Livestock(CommonInfo): """Model definition for Livestock. CommonInfo is an abstract model that contains created_by, modified_by, date_created, date_modified and comment fields""" product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='livestock') date = models.DateField( auto_now=False, auto_now_add=False) production = models.PositiveIntegerField( 'Livestock produced (Kg or litre or #)') number_of_animal = models.PositiveIntegerField( 'Number of Animals (Quantity)', blank=True, null=True) cost_of_production = models.PositiveIntegerField( 'Cost of Production (GYD)', blank=True, null=True) views.py class LivestockCreateView(LoginRequiredMixin, PermissionRequiredMixin, CreateView): model = Livestock form_class = LivestockForm success_url = reverse_lazy('real:livestock-list') template_name = "real/livestock/livestock_form.html" permission_required = ('real.add_livestock') def get_initial(self): initial = super(LivestockCreateView, self).get_initial() initial['date'] = timezone.now() return initial def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) Forms.py class LivestockForm(forms.ModelForm): """Form definition for Livestock.""" class Meta: """Meta definition for Livestockform.""" model = … -
Autofill foreignkey in Django Admin Inline
I have Employee shown inline with Company. Employee belongs to a Company and a company specific Department. I have to autofill the current company to the new Department form. # models.py class Company(models.Model): name = models.CharField(max_length=255) class Department(models.Model): name = models.CharField(max_length=255) company = models.ForeignKey("Company", on_delete=models.CASCADE) class Employee(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE) company = models.ForeignKey("Company", on_delete=models.CASCADE) department = models.ForeignKey("Department", on_delete=models.CASCADE) Edit Company Page New Department Popup -
Intergrating Django with React Frontend: Is a REST API Needed
so I am trying to connect my back-end Django to my front-end React. Now the front-end react is essentially completed and running on a node server to check it out. I want to integrate it into my Django to use as a back-end. My first thing i want to do is set up the login and register page. I have most of the django back-end done but now i need to get the information like the email and password from the React to Django. The HTML for EMail and Password <form action="/authentication/" method ="POST"> {% csrf_token %} Email : <input type="email" name="email"><br><br> Password : <input type="password" name="pass"><br><br> <input type="submit" value="Login"> <button type="button" onclick="location.href='{% url 'register' %}'">Register</button> </form> the react text field for just the email looks like this: <TextField variant="outlined" margin="normal" required fullWidth id="email" label="Email Address" type="email" name="email" autoComplete="email" autoFocus /> Django def user_login(request): return render(request, 'user_login.html') # page which user will login at def authentication(request): email = request.POST.get('email') passwrd = request.POST.get('pass') try: user = authen.sign_in_with_email_and_password(email, passwrd) except Exception as E: # Where login fails goes message = "Credentials Wrong" return render(request, 'user_login.html', {'message':message}) # sends message login failed My first question is do i need to create a separate … -
django jsignature not saving to database
i am trying to implement a jsignature plug in to my django appplication via django-jsignature3 , however it seems that i am unable to get it to save to my database. here is my code: models.py class JSignatureModel(JSignatureFieldsMixin): name = models.CharField(max_length=20) views.py def my_view(request): form = SignatureForm(request.POST or None) print('in view') if form.is_valid(): signature = form.cleaned_data.get('signature') print('form is valid') if signature: # as an image print('found sig') signature_picture = draw_signature(signature) # or as a file signature_file_path = draw_signature(signature, as_file=True) return render(request, 'cash/jsig.html', {'form': form }) jsig.html {% extends 'base.html' %} {% load static %} {%load crispy_forms_tags%} {% block content %} <body> {{ form.media }} <form action="." method="POST"> {% for field in form %} {{ field.label_tag }} {{ field }} <span style="color:red">{{ field.errors }}</span> {% endfor %} <input type="submit" value="Save"/> {% csrf_token %} </form> </body> {%endblock content%} url.py path('jsig/', views.my_view , name='jsig') forms.py (this is really iffy to me , i don't understand the documentation , there is no place that my model was called , hence i did this my self but it does not work) class SignatureForm(forms.Form): signature = JSignatureField() class Meta: model = JSignatureModel fields = ['name','signature'] exclude = [] here is my console [04/Apr/2020 01:14:43] "GET /jsig/ … -
Django Runtime Error while trying to run server
I am trying to run my Django server via 'python manage.py runserver' on a github repository i cloned and always get this runtime error message: class AbstractBaseUser(models.Model): RuntimeError: ____class____ not set defining 'AbstractBaseUser' as <'class 'django.contrib.auth.base_user.AbstractBaseUser'>. Was ____classcell____ propagated to type.____new____? Details of installed packages in my virtual environment are: Django 1.9 | django-crispy-forms 1.6.0 | django-markdown-deux 1.0.5 | django-pagedown 0.1.1 | markdown2 2.3.1 | olefile 0.46 | Pillow 7.1.1 | pip 19.2.3 | setuptools 41.2.0 | I am using python version 3.8.1 please does anyone have any suggestions on how to solve this error. Thank you. -
Can I remove the null=True parameter from a django ForeignKey?
I have two models, foo and bar. They already exists in my database with many instances each. Now, I realized that there is a relation that should be added. Therefor, I wish to add a ForeignKey betweenfoo and bar. class foo(): # lots of stuff bar = models.ForeignKey(bar, related_name='foo', null=True) I actually don't want the key to be nullable, but since they already exists, I need to add it because the existing rows need to be populated. Can I later remove the null=True parameter once all instances have the foreignKey field are populated? -
Setting value of certain attribute of a model related to User
I have a model related to User (relationship: OneToOne), in this model I have a field named email_confirmation. I can access to this field but I can't updated it. models.py class Profile(models.Model): profile_user = models.OneToOneField(User, ...) profile_email_confirmation = models.BooleanField(default=False) views.py def mail_confirmation(request, uidb64, token): uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) ... if user is not None and account_activation_token.check_token(user, token): user.profile.profile_email_confirmation = True user.save() #This isn't working and doesn't cause any error login(request, user) #This is working return redirect('/home') #This is working This function isn't causing any error so I don't know what is wrong I actually get redirect to /home (logged). I also can access to the field profile_email_confirmation When I check the model in the Admin page, the profile_email_confirmation field has not been altered. -
Django (fields.E304) - AbstractUser
I would like to create new fields in the model of the Django's User system. I am following the official documentation, but I keep getting the same error: My changes so far to the code have been the following: models.py: from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): bio = models.TextField(max_length=500,blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User admin.site.register(User, UserAdmin) -
How to organize the applications in django project
I getting started with Django. I want to build a work_manager website with the following content: hour calculation - enter shifts per day and can view the hours per day, week and month. shift for each week(maybe a month too) - view table for all the schedules of the employees. salary calculation per employee for month. And maybe in the future more things. For start I have this DB structures: Now, my question is what is the recommended way to organize the project? I searched here and find some people the recommended putting all in one app because strong relations between the models can cause problems if you split into several apps. And some other people recommended to split it that each I can explain each app with one sentence (like I did here up). So, what is the best practice for that? If to split so how to arrange the models? Thank You! -
Issue with django at runserver command
im new in django and i have suposedly a really simple issue which is driving me crazy. once i create superuser and hit the runserver command i go to the http://127.0.0.1:8000/admin/ enter acc and pass and server throws me out. enter image description here on random basis i sucseed in entering the admin panel, but once i get in and press anything it again throws me out and i see the below message enter image description here any ideas how i can fix this? -
How to get my Django template to recognize a model method?
In my django template <p>This user is unsubscribed {{sub.is_unsubscribed}}</p> always displays "This user is unsubcribed False" even when it should show True based on the following models.py from django.shortcuts import get_object_or_404 class Subscriber(models.Model): email = models.CharField(max_length=12) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) create_date = models.DateTimeField(auto_now_add=True) def is_unsubscribed(self): try: get_object_or_404(MasterUnsubscriber, unsubcriber_email=self.email) return True except: return False def __str__(self): return self.email class MasterUnsubscriber(models.Model): unsubscriber_email= models.CharField(max_length=12) And for structural reasons of my app, I do not want to move the unsubscribe to the Subscriber model as a boolean. How can this be resolved while keeping same model formats. -
Image created in views isnt being rendered in template django
Im trying to render a simple graph that i create with matplotlib in my template. I want to render the graph in the body of the page not just return an HttpResponse with that graph. But i cant get it to work. Here is what i tried. views.py code def showGraph(request): content_x = [10, 20, 30] content_y = ['one', 'two', 'three'] plt.bar(content_x, content_y) plt.title('Some chart') plt.show() buffer = io.BytesIO() canvas = plt.get_current_fig_manager().canvas canvas.draw() graphIMG = PIL.Image.frombytes('RGB', canvas.get_width_height(), canvas.tostring_rgb()) graphIMG.save(buffer, "PNG") content_type = "Image/png" buffercontent = buffer.getvalue() graphic = (buffercontent, content_type) plt.close() return render(request, 'projectRelated/LAN/graphs.html', {'graphic': graphic}) html page code {% extends 'base.html' %} {% load static %} {% block container_content %} <img src="data:image/png;base64,{{ graphic }}"> {% endblock container_content %} The above code just displays a random icon.. -
JQuery-File-Upload using Signed_URL Google Storage, how to call super class function data.submit() within ajax callback?
I have a fileupload HTML element in my DOM and it currently gets multiple files and calls "add" function for each file. For each file, a signed url is received from an ajax call to the related api. After the succesful ajax call to api, I want to call the data.submit() method of the parent function which is the function in fileupload method as first argument. How may I be able to access that just after "xhr.setRequestHeader('Content-Type', file.type);" ? The primary inspiration is from this link :http://kevindhawkins.com/blog/django-javascript-uploading-to-google-cloud-storage/ $("#fileupload").fileupload({ dataType: 'json', sequentialUploads: true, add: function(e, data) { $.each(data.files, function(index, file) { // pack our data to get signature url var formData = new FormData(); formData.append('filename', file.name); formData.append('type', file.type); formData.append('size', file.size); // Step 3: get our signature URL $.ajax({ url: '/api/getsignedurl/', type: 'POST', processData: false, contentType: false, dataType: 'json', headers: { 'X-CSRFToken': Cookies.get('csrftoken'), }, context: 'hello', data: formData, }).done(function (data) { // Step 5: got our url, push to GCS const xhr = new XMLHttpRequest(); if ('withCredentials' in xhr) { xhr.open("PUT", data.signed_url, true); } else if (typeof XDomainRequest !== 'undefined') { xhr = new XDomainRequest(); xhr.open("PUT", data.signed_url); } else { xhr = null; } xhr.onload = () => { const status = … -
How to stop Django PasswordInput prefilling form
I am trying to create a django form to allow users to login. forms.py class LoginForm(forms.ModelForm): username = forms.CharField(label='User name', max_length=30) password = forms.PasswordInput() class Meta: model = User fields = '__all__' widgets = {'password': forms.PasswordInput()} views.py def login_view(request): form_context = {'login_form': LoginForm,} url = "users/login.html" if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) ... else: context = form_context return render(request, url, context) login.html <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ login_form.username.label_tag }}</td> <td>{{ login_form.username }}</td> <td rowspan="2"><button type="submit" class="btn btn-success">Login</button></td> </tr> <tr> <td>{{ login_form.password.label_tag }}</td> <td>{{ login_form.password }}</td> </tr> </table> </form> The problem I have is that if the line widgets = {'password': forms.PasswordInput()} is used, then the form is pre-filled with username and password If the line is commented out, the the form is not prefilled, but the password is in plain text. What is wrong here? -
What do you think about my idea to build my personal finance tracker with Django - too ambitious? [closed]
I would love to have feedback on my idea. Thanks in advance :) First of all: Im relatively new to Python and Programming in general. I did a lot of tutorials, learned the standard syntax and tried out a lot of modules. I feel like I don't learn enough anymore and want to have my first real big project to really get out of the watch-tutorial-flow and really learn the modules by working with them. My idea: A personal finance tracker: I thought about using Django, because i want to learn a popular Web-Framework. I thought about dividing it into different apps: In one app you should be able to input data of the expenses(price, category, automatic timestamp, etc.) that is going to be saved to a database (sqlite) In another app you should have an (interactive) dashboard, that uses the data from the database and plots some graphes etc. optional: User-System to make the Webapp usable for other people Update sqlite to MySQL or other bigger databases Use some API or something to get data from your bank, so you don't need to manually type in the expenses My questions: Is the project too ambitious/to big? As I already … -
Is possible to update or create objects just using django bulk_create
In some cases I need to update existing objects in others I need to create them. It is possible to use a mixed list of updated/created objects to bulk_create() so I don't have to use save() for the updated objects? -
Synchronized Model instances in Django
I'm building a model for a Django project (my first Django project) and noticed that instances of a Django model are not synchronized. a_note = Notes.objects.create(message="Hello") # pk=1 same_note = Notes.objects.get(pk=1) same_note.message = "Good day" same_note.save() a_note.message # Still is "Hello" a_note is same_note # False Is there a built-in way to make model instances with the same primary key to be the same object? If yes, (how) does this maintain a globally consistent state of all model objects, even in the case of bulk updates or changing foreign keys and thus making items enter/exit related sets? I can imagine some sort of registry in the model class, which could at least handle simple cases (i.e. it would fail in cases of bulk updates or a change in foreign keys). However, the static registry makes testing more difficult. I intend to build the (domain) model with high-level functions to do complex operations which go beyond the simple CRUD actions of Django's Model class. (Some classes of my model have an instance of a Django Model subclass, as opposed to being an instance of subclass. This is by design to prevent direct access to the database which might break consistencies and … -
Django generic relations, unique together and abstract models
I have a Tag model and an intermediate model to relate it class Tag(models.Model): name = models.CharField(max_length=255) slug = models.CharField(max_length=255, blank=True) class TagIntermediate(models.Model): # Relation to custom content model content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() customcontent = GenericForeignKey('content_type', 'object_id') # Relation to tag tag = models.ForeignKey(Tag, on_delete=models.CASCADE) class Meta: unique_together = ["content_type", "object_id", "tag"] I add this to an abstract base class class BaseModel(models.Model): blog_tags = GenericRelation('TagIntermediate') class Meta: abstract = True And then I define two models derived from it class ModelOne(BaseModel): model_one_field = models.CharField() class ModelTwo(BaseModel): model_two_field = models.CharField() When I now create a Tag object and add it to a ModelOne object and a ModelTwo object, then I get the message triggered by my "unique together" definition: The combination of content_type, object_id and tag does already exist. Why? ModelOne and ModelTwo should be two different content_types, right? Or did I forget something? I`m using Django Version 3.0.4