Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
change default label of UserCreationForm
I Want to change default label of django UserCreationForm which I imported from django.contrib.auth.forms from django.contrib.auth.forms import UserCreationForm class SignupForm(UserCreationForm): class Meta: model = models.User fields = ['username', 'email', 'password1', 'password2'] e.g. here how should I change the default label or error message of username? -
how to fix Git error when trying to push -- pre-receive hook declined
I was trying to push what i have in my app using Django python to be deployed to Heroku and keep getting this error : ! [remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/immense-brushlands'` requriment.txt file is there : asgiref==3.4.1 beautifulsoup4==4.10.0 certifi==2021.10.8 cffi==1.15.0 charset-normalizer==2.0.7 cloudinary==1.26.0 cryptography==35.0.0 defusedxml==0.7.1 Deprecated==1.2.13 dj-database-url==0.5.0 Django==3.2.5 django-bootstrap4==3.0.1 django-braces==1.14.0 django-heroku==0.3.1 django-oauth-toolkit==1.5.0 django-rest-framework-social-oauth2==1.1.0 djangorestframework==3.12.4 gunicorn==20.1.0 idna==3.3 jwcrypto==1.0 oauthlib==3.1.1 psycopg2==2.9.1 pycparser==2.20 PyJWT==2.3.0 python3-openid==3.2.0 pytz==2021.3 requests==2.26.0 requests-oauthlib==1.3.0 six==1.16.0 social-auth-app-django==5.0.0 social-auth-core==4.1.0 soupsieve==2.2.1 sqlparse==0.4.2 stripe==2.59.0 urllib3==1.26.7 whitenoise==5.3.0 wrapt==1.13.2 my Procfile in root directory and contain: web : gunicorn foodhub.wsgi -
Django external authentication (allauth) redirect to diffrent locations with diffrent providers
I have three ways to sign in (github, google, reddit). I want to redirect individually after login with these different providers. Right now it redirects all types of login to this location: LOGIN_REDIRECT_URL = '/' How to specify different locations for different providers? -
Is this way of using assertRaises overkill?
I have the following method : def create_user(self, email, password, last_name, first_name): # (...) where all four parameters are mandatory. When testing this method, should I check with assertRaises whether a TypeError is thrown when one of the parameters is missing ? It would be pretty tedious to do have to write this : #(...) with self.assertRaises(TypeError): User.objects.create_user() User.objects.create_user(email='') User.objects.create_user(password='') User.objects.create_user(first_name='') User.objects.create_user(last_name='') User.objects.create_user(email='', password='') User.objects.create_user(email='', first_name='') User.objects.create_user(email='', last_name='') User.objects.create_user(first_name='', last_name='') User.objects.create_user(first_name='', password='') User.objects.create_user(last_name='', password='') User.objects.create_user(email='', first_name='', last_name='') User.objects.create_user(email='', first_name='', password='') User.objects.create_user(email='', last_name='', password='') User.objects.create_user(first_name='', last_name='', password='') What is the method had more mandatory parameters ? -
Not getting cookie in Django
pretty new to Django and I am having a hard time solving a situation on a project that I am working on. I am setting my cookies via JS as JSON and trying to request them in the backend. My code for the JS is: function getCookie(name) { // Split cookie string and get all individual name=value pairs in an array var cookieArr = document.cookie.split(";"); // Loop through the array elements for(var i = 0; i < cookieArr.length; i++) { var cookiePair = cookieArr[i].split("="); /* Removing whitespace at the beginning of the cookie name and compare it with the given string */ if(name == cookiePair[0].trim()) { // Decode the cookie value and return return decodeURIComponent(cookiePair[1]); } } // Return null if not found return null; } var cart = JSON.parse(getCookie('cart')) if (cart == undefined){ cart = {} console.log('Cart Created!', cart) document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/" } console.log('Cart:', cart) The cookie is made After that I try to get to cart cookie in the backend. Also the items added to the cart are displayed in the console. Console info My backend code is: def cart(request): print(request.COOKIES) if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False, ) items = … -
Check record signature against each person in the approver list in Django
I have following model class set up: class Moc(models.Model): .....my other fields..... def __str__(self): return self.moc_title def get_absolute_url(self): return reverse('moc_content_update', kwargs={'pk': self.pk}) class Verifier(models.Model): moc = models.ForeignKey(Moc, related_name='verifiers', on_delete=models.CASCADE, default='1') verifier_group = models.CharField(max_length=36, blank=True, null=True) verifier_name = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE,) verify_due = models.DateField(blank=True, null=True) def __str__(self): return str(self.id) def save(self, *args, **kwargs): created = not self.pk super().save(*args, **kwargs) if created: VerifierSignOff.objects.create(verifier=self) class VerifierSignOff(models.Model): verifier = models.OneToOneField(Verifier, related_name='verifiersignoff', blank=True, null=True, on_delete=models.CASCADE) approve = models.BooleanField(default=False) reject = models.BooleanField(default=False) signoff_date = models.DateField(auto_now=True) note = models.TextField(max_length=256, blank=True) def __str__(self): return str(self.id) My views are stetted up to create Moc instance, add Verifiers (in total 3 users) with respective VerifierSignOff and display it on my template without any issue. My views.py: def verify_coordinate_view(request, pk): moc = get_object_or_404(Moc, pk=pk) # I guess I need to have MOC Status logic here return render(request, 'moc/moc_content_verification.html', context={'pk':pk, 'moc':moc, }) def verifier_signoff_view(request, pk): verifiersignoff = VerifierSignOff.objects.get(pk=pk) form = VerifierSignForm if request.method == 'POST': form = VerifierSignForm(request.POST, instance=verifiersignoff) if form.is_valid(): form.save(commit=False) if verifiersignoff.approve is True and verifiersignoff.reject is True: return HttpResponseForbidden('You have either APPROVE or REJECT - operation not allowed!') else: form.save() return redirect('verify_coordinate', pk=verifiersignoff.verifier.moc_id) # return redirect('index') else: return render(request, 'moc/verify_signoff.html', context={'verifiersignoff': verifiersignoff, 'form': form}) I am displaying everything … -
Problem with many-to-many relation : model is not found in app : "has not been installed"
that's my first post on stackoverflow. Let me know if I can improve my post. I tried to re-launch an old project. The architecture is composed of 2 apps: blog authentication blog.models contains : class BlogContributor(models.Model): contributor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) blog = models.ForeignKey(Blog, on_delete=models.CASCADE) contribution = models.CharField(max_length=255, blank=True) class Meta: unique_together = ("contributor", "blog") authentication.models : class User(AbstractUser): CREATOR = "CREATOR" SUBSCRIBER = "SUBSCRIBER" ROLE_CHOICES = ( (CREATOR, "Créateur"), (SUBSCRIBER, "Abonné"), ) profile_photo = models.ImageField(verbose_name="photo de profil") role = models.CharField(max_length=30, choices=ROLE_CHOICES, verbose_name="rôle") follows = models.ManyToManyField( "self", limit_choices_to={"role": CREATOR}, symmetrical=False, verbose_name="suit", ) blogs = models.ManyToManyField( "self", through="BlogContributor", related_name="contributors", ) An issue occurs : authentication.User.blogs: (fields.E331) Field specifies a many-to-many relation through model 'BlogContributor', which has not been installed. I tried : to import BlogContributor in the file to import BlogContributor in authentication init.py When I do the last action another issue occurs : raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
How to annotate a define a query in django with authenticated
I want to do a django filter that is ordered by authenticated user. Something like this, but the authenticated users objects first in the returned queryset: user = self.request.user Company.objects.filter(status="approved") The Company model has a foreign key user as below: Company(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, default=1, on_delete=models.CASCADE, related_name="companies", ) Note: I am NOT trying to get just the user's objects. -
How to create a user in Django with extra fields
I want to know how do I create users in Django. I can use User.objects.create_user() but I can only store username, email, password, first name, last name. I see that django.contrib.auth.forms is depreciated so I cannot UserCreationForm. What if I want to store more fields. Can anyone help me with it? -
using object.filter() on chart.js
So I have this chart that shows me the name of a candidate and their respective votes $(document).ready(function(){ const ctx = document.getElementById('myChart').getContext('2d'); Object.filter = (object,objectItems) => Object.fromEntries(Object.entries(object).filter(objectItems)); const President = Object.filter(ctx, ([position, votes])=> position == 'President'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for i in qs %} '{{i.last_name}} {{i.position}} {{i.partylist}}', {%endif%} {% endfor %}], datasets: [{ label: '# of Votes', data: [{% for i in qs %} {{i.votes}}, {% endfor %} ], backgroundColor: [ {% for i in qs %} 'rgba(54, 162, 235, 0.2)', {% endfor %} ], borderColor: [ {% for i in qs %} 'rgba(54, 162, 235, 0.2)', {% endfor %} ], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); }); </script> and the views.py for it is like this class PollsView(TemplateView): template_name = "test.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context ['qs'] = Candidate.objects.all() return context now what I wanted to do is to filter all the candidates by their position. i.e Candidate1 is President etc. and show those in the charts. I've tried using objects.filter(position = 'President') in the view but I got ValueError field 'id' expected a number but got 'President', … -
How can I use Celery in Django with just the DB?
Looking at https://docs.celeryq.dev/en/v5.2.7/getting-started/backends-and-brokers/index.html it sounds pretty much as if it's not possible / desirable. There is a section about SQLAlchemy, but Django does not use SQLAlchemy. In way older docs, there is https://docs.celeryq.dev/en/3.1/getting-started/brokers/django.html . Is it possible with recent Celery / Django versions to use Celery with just the database for storing messages / results? -
Deploy Django with React JS App on CentOS 7
I have Django with react JS project after uploaded to VPS CentOS 7 my domain showing page not found -
How to order parent table field by count of child table fields
i hope i wrote the title correctly. i just started django recently, and i have problem with queryset. so i have these models, views and template file. models.py class Topic(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name views.py def topics(request): """topics page for listed view of topics""" room_count = Room.objects.all().count() topics = Topic.objects.all() context = {'topics': topics, 'room_count': room_count} return render(request, 'base/topics.html', context) topics.html {% for topic in topics %} <li> <a href="{% url 'home' %}?q={{topic.name}}">{{ topic.name }}<span> {{topic.room_set.all.count}}</span></a> </li> {% endfor %} this loop clearly sorts topics by its created time. but I want it to be sorted by new POST request in room field. how can I do this? I tried several attempts, but it doesn't solve the issue. Or should I change my database architecture? since I'm fairly new to databases, I'm having a headache to solve this issue. I've been googling for two or three days but I couldn't find a solution. thanks in advance. -
Redirected to admin reset_password and change_password template instead of my app template
I use Django registration and override reset_password and change_password views. But it works in all my projects except my last project where I'm redirected to admin templates instead of my own templates. Django 2.2.5/Docker settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'registration.apps.RegistrationConfig', ] urlpatterns = [ path('authentification/', include('registration.urls')), path('registration/', include('django.contrib.auth.urls')), ] app_name='registration' urlpatterns = [ path('password_reset/', views.ResetPasswordView.as_view(success_url="/registration/login/"), name='password_reset'), path('password_change/', views.CustomPasswordChangeView.as_view(), name='password_change'), ] class ResetPasswordView(SuccessMessageMixin, PasswordResetView): template_name = 'registration/password_reset_form.html' ... success_url = reverse_lazy('home') class CustomPasswordChangeView(SuccessMessageMixin, PasswordChangeView): form_class = CustomPasswordChangeForm template_name = 'registration/password_change_form.html' success_url = reverse_lazy('home') -
How to display the information contained in a related model's field in Django template
In my application I have the following two models: class CondRecordHdr(models.Model): cond_prices_id = models.AutoField(primary_key=True, verbose_name='Cond ID') cond_type = models.ForeignKey(AlliedPriceCondType, ... material = models.ForeignKey(Material, ... class Dependency(models.Model): cond_dependency = models.AutoField(primary_key=True, ... prc_cond_hdr = models.ForeignKey(CondRecordHdr, ... prc_select_obj = models.CharField(max_length=15, ... I am placing the objects of the first model in the listview with: class CondRecListView(ListView): context_object_name = 'obj_context' model = CondRecordHdr template_name = ... def get_queryset(self): return CondRecordHdr.objects.order_by(... Then I am using the context object to display the data in a tabular form in the template. I am displaying the data like this: Cond Type Material Dependency (Note1) Xyz More fields TCHG Mouse blank abc1 IPRO Keyboard abc2 Note 1: In this column I want to display the value of field prc_select_obj model Dependency, where I have no data being displayed currently (blank). How do I display the information contained in model Dependency in the same template (in column shown above Note1)? -
PostgreSQL DB changes time when I import data from CSV-file
I have a CSV file of table with datetime attribute like '2016-04-03T00:00:00', when I copy this CSV to my PostgreSQL table it changes time to '2016-04-02 21:00:00+00' (I have timestamp with tz in this table cause table attribute of timestamp is created by Django DateTimeField which can only have timestamp with timezone), how to avoid time change and to get timestamp in PostgreSQL like ''2016-04-02 00:00:00+00' after copying. Added screen of my CSV and table result. -
how to add multiple contents in google maps info windows in django with javascript
I am using the Django framework. I created multiple markers and info windows with images in it on Google Maps. It works well so far but some users have multiple items and on the map just one item is shown. I want these items to be seen at same info window or indifferent. models.py class Customer (models.Model): user= models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True) latitude = models.CharField(verbose_name="Latitude", max_length=50, null=True, blank=True) longitude = models.CharField(verbose_name="Longitude", max_length=50, null=True, blank=True) def __str__(self): return self.name class Product(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) description = models.CharField(max_length=200, null=True, blank=True) item_pic = models.ImageField( null=True) map js code inside the html function initMap() { var markers2=[] {% for product in products%} var lats = '{{ product.customer.latitude }}' var lats2 = parseFloat(lats) var lg = '{{ product.customer.longitude }}' var lg2 = parseFloat(lg) var mark = {coord:{lat:lats2,lng:lg2}, content : "<div >'<div class ='box small' style='float:left'; ><a href= {% url 'indexitem' product.id %} style = 'font-size:16px; text-decoration:none; color:black'><img id='surf1' src='static/images/{{product.item_pic}}'><br></div><div style='float:right; padding: 10px; font-size:14; '><b>{{product.name}}</b><br><b>${{product.price|floatformat:2}}</b> </div>", content2 : "<div >'<div class ='box small' style='float:left'; ><a href= {% url 'indexitem' product.id %} style = 'font-size:16px; text-decoration:none; color:black'><img id='surf1' src='static/images/{{product.item_pic}}'><br></div><div style='float:right; padding: 10px; font-size:14; '><b>{{product.name}}</b><br><b>${{product.price|floatformat:2}}</b> </div>", … -
django rest framework override save() method
When I override the save() method, the create() method is called inside, but when I add a read-only field uuid, the field is not serialized. serializer.py class AwsUploadFileSerializer(serializers.ModelSerializer): extract_file_name = serializers.CharField(source='extract_file.name', read_only=True) class Meta: model = ExtractAWSFile fields = [ 'uuid', 'extract_file', 'extract_file_name' ] extra_kwargs = { 'extract_file': {'write_only': True} } def save(self, **kwargs): instance: ExtractAWSFile = super().create(self.validated_data) res = upload_file_to_aws(instance.extract_file.path) if not res: instance.extract_file.delete() instance.delete() return instance response { "extract_file_name": "tets3.jpg" } So I'm trying to call the save() method of the parent class so that the uuid field can be serialized, but there is something wrong with the file name field I wrote earlier and it will take the path with it instead of just displaying the name. serializer.py class AwsUploadFileSerializer(serializers.ModelSerializer): extract_file_name = serializers.CharField(source='extract_file.name', read_only=True) class Meta: model = ExtractAWSFile fields = [ 'uuid', 'extract_file', 'extract_file_name' ] extra_kwargs = { 'extract_file': {'write_only': True} } def save(self, **kwargs): instance = super().save(**kwargs) res = upload_file_to_aws(instance.extract_file.path) if not res: instance.extract_file.delete() instance.delete() return instance response { "uuid": "c4aea74e-3748-4c05-8d6c-2413b1eebcc6", "extract_file_name": "extractAWS/2022/10/08/tets3.jpg" } Why is that? I'm wondering what I should do after save() to properly display the uuid field -
Ajax addEventListener stops working after first click
I am trying to populate a calendar with Ajax with Django backend. The code works just fine when I load the page and click id="wp-calendar-nav-next" and it populates the calendar as per my requirement. However it doesn't work after the first click. How do I recode it to make sure id="wp-calendar-nav-next" works constantly. I am trying to fix this before coding id="wp-calendar-nav-prev". <div class="widget-calendar-container " id="django-calendar"> <div class="calendar-header"> <div class="wp-calendar-nav-prev" id="wp-calendar-nav-prev"> <a>Jan</a> </div> <div class="calendar-title" id="cur_mon">{{ activity_month|title }}</div> <div class="wp-calendar-nav-next" id="wp-calendar-nav-next"> <a>Mar</a> </div> </div> <table id="wp-calendar" class="wp-calendar-table"> <thead> <tr> <th scope="col" title="Sunday">Sun</th> <th scope="col" title="Monday">Mon</th> <th scope="col" title="Tuesday">Tue</th> <th scope="col" title="Wednesday">Wed</th> <th scope="col" title="Thursday">Thu</th> <th scope="col" title="Friday">Fri</th> <th scope="col" title="Saturday">Sat</th> </tr> </thead> <tbody id="ajax-calendar"> <tr> {% for day in c_monthdays %} <td {% if day == activity_day %} class="calendar-viewing" {% endif %}> <div class="calendar-day-content"> {% if day == 0 %} {% else %} <a href="{% url 'calendermonthday' activity_month day %}" class="ga-calendar-day-link"> {{ day }} {% endif %} </a> </div> </td> {% if forloop.last %} </tr> {% elif forloop.counter|divisibleby:"7" %} </tr> <tr> {% endif %} {% endfor %} </tbody> </table> </div> Below is the script: <script> const loadBtnNext = document.getElementById('wp-calendar-nav-next'); function load_next_month() { var current_month = document.getElementById('cur_mon').textContent; const content_container = document.getElementById("django-calendar"); … -
drf_yasg manual parameters configuration
I am working with drf_yasg for the very first time and I am curious to know what does IN_QUERY and the other options provided by OPENAPI do. I can't find an explanation for the purpose of these options in the documentation. -
How to retrieve data from a table and display it with Python and Django in an html file?
for the purposes of an introductory course in python, Django and Postgresql, I am looking for the best way to retrieve table data and display it in a structured way in an html file with Django and python as a tool and language. Thank you all for your responses -
Google Registration, jwt staying logged in
I just added a feature to be able to register with Google. For security reasons I added a field in the db that is false if the user is registered the usal way(Username & PW) and true if he is registered with google. class CustomUser(AbstractUser): objects = UserManager() REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' username = models.CharField(max_length=40, unique=False,null=True, blank=True) email = models.EmailField(_('email address'), unique=True) profile_image = models.ImageField(null=True,blank=True,default = "users.png",upload_to='',) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False) telephone = models.CharField(blank=True, max_length=20, null=True) email_is_verified = models.BooleanField(default = False, null=False, blank = False) currentVerificationToken = models.CharField(max_length = 6, default="000000") withGoogleRegistered = models.BooleanField(default = False) def __str__(self): return self.email So if you try to login the usal way but the email adress is bounded to an google registered account, you wont be able to. If you try to login with a usal way bounded email adress, but its connected to a google bounded account , you wont be able to. So, I made this in order to seperate betweena accounts with a password and accounts without a password... But there is a little problem now. In Order to obtain an refresh token (JWT) I have to give a username and a password, otherwise … -
How to use a raw query in Django that uses an external database as well as a Django model
I have an external database with source data. (Microsoft db) How can I query this database and do an inner join on a Django model? I have two connections set up in settings.py This way I can acces the external database like this: "with connection['externalDB'].cursor() as c:" This external db has millions of records. I want run a query and then save that model into another Django model. SELECT product ,client FROM [external db] INNER JOIN [django model] WHERE client = 'foo' What would be the best way to approach this? -
How to perform eth contract transaction in Django using web3.py and Metamask
Trying to build a Dapp using Django, till now completed below steps. Deployed a simple lottery contract on test net, contract address is 0xD5d56C139848A0E55DC5C616D04a0CeD98D8BeA3 (can be seen at https://sepolia.etherscan.io/) Using web3.py I can connect to this contract and call the functions. I have created a simple webapp which ask user to connect to its Metamask wallet. I am using JS to load the Metamask wallet in the browser. When user click on connect wallet Metamask extension loads in the browser. Once user gets connected I can read the address of the connected user address. Next step is user will click on enter lottery button, after that Metamask should popup to sign the transaction. The Problem is I want to use the web3.py in my Django view to call my contract function which will allow user to enter in to the lottery game, but how can I call Metamask from Django view to ask user to sign transaction as it is browser extension. -
Filter django admin list with text input
Based on django ModelAdmin document for filterize list data, exist some class in admin that making filters, like DateFieldListFilter, ChoicesFieldListFilter and etc, But dosent exist any class for text input field. I need to use several text input fields for filter my model list data in admin page. What can i do?