Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use tablespace in django for this model
I have some models with relations and i need to to use tablespace in that models , please help how i solve it . class Teacher(models.Model): # classe 365's id of the teacher classe_365_id = models.CharField(unique=True, max_length=50) # email of the teacher email = models.EmailField(max_length=254) # first name of the teacher first_name = models.CharField(max_length=50) # last name of the teacher last_name = models.CharField(max_length=50) # Many to Many fiels with the subject, because a teacher can teach multiple subjects # and also a subject can be taught by many teacher in same class subjects = models.ManyToManyField('Subject') #status for teacher is active or not # status = models.BooleanField(default=True) def __str__(self): return self.first_name + self.last_name -
How to share data between auth users Django
I have a list of projects in my Django which is created by some auth user, so I want to share specific projects with some other users as well. for example, I have created a "project ABC" from my frontend app so what if I want to share that "project ABC" with some other account? something like access control functionality. you can see the account in the Project model below, so currently one account can hold the project but I want to share that Project with others as well. models.py class Project(models.Model): name = models.CharField(max_length=255, default='') description = models.CharField(max_length=255, default='') created_at = models.DateTimeField(auto_now=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) is_active = models.IntegerField(default=1, null=True) account = models.ForeignKey(User, on_delete=models.CASCADE, null=True) -
Django Admin saving model twice - Is It Django (version 3.1) BUG?
Hy everyone, lately I was developing LMS, and I noticed a weird behavior, Django Admin is saving model twice, and am sure I click "save" button only once. Just to make sure its not bug in my code, I made a fresh new project with single model and simply registered it with no modification in admin class and still got the same weird behavior. My code: models.py admin.py Pipfile When I saved a test model with title "record 1", it saved it twice: I didn't modified anything else. Please help -
Django models does not create table after I clone it on github
Recently I'm doing a small Django project that I have to work with my teammates, so I clone the project's repository from github. The problem is , the database in my computer doesn't have the table so i think i have to makemigrations and migrate it. But after i did that,django only createed its own tables but didn't create another tables that my teammates wrote in Django's modles. I really need your guys hlep this are the models my teammates wrote but after i makemigrations and migrate it phpmyadmin does not show the tables i want enter image description here enter image description here -
Django app incorrect datetime during deployment
I have a django model with a datetime field like this: date_creation = models.DateField(auto_now_add=True) Locally, on my machine, this control is created with the local date and time. When the application is deployed the field is not created with local time. I tried to do this: date_creation = models.DateField(default=datetime.now()) It does not work. How to solve this problem ? I am in central Africa -
Provide short_description for model field in Django Admin
Sometimes I want to display many boolean fields in the list_display view in Django Admin. Unfortunately these fields come with a long verbose_name which gives very ugly and large columns. I know that you can provide a short_description attribute to callables for providing column names in the list_display view in Django Admin. So I reverted to doing this: class MyModelAdmin(admin.ModelAdmin): list_display = ['id', 'field1', 'field2', 'short_boolfield3', 'short_boolfield4'] def short_boolfield3(self, obj): return obj.boolfield3 short_boolfield3.short_description = 'fld3' short_boolfield3.boolean = True def short_boolfield4(self, obj): return obj.boolfield4 short_boolfield4.short_description = 'fld4' short_boolfield4.boolean = True Which works, but is definitely against DRY, especially when you have many boolean fields. Is there a short_description equivalent for Model fields? -
Oauth Bearer token throws an error when trying to access an api?
I have djangorestframework-simplejwt for jwt authentication and for oauth i have used drf-social-oauth2. The access token works when users login from simplejwt but the access token provided by the url /convert-token/ throws an error like this:It was working fine without simplejwt. Is there anything i need to add? { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } -
Remove a field which was Primary Key in models.py
I have a model with the following fields: email = models.EmailField(verbose_name="email", max_length=60, unique=True) department = models.TextField(verbose_name="department") username = models.CharField(max_length=30, unique=True) emp_id = models.AutoField(primary_key=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) hide_email = models.BooleanField(default=True) name = models.TextField(verbose_name="employee name") I want remove emp_id field, as you can see it is the primary key field. Can you please create a migration file for the same? Thank you -
How to check with decorator if user has access to some objects in Django
I'm working on a project, with structure as below. And I was trying to check if user is a member of the requested team and is allowed to see it's details. So I was trying to achieve this by decorators, but i'm still getting http 500 error. I'm not sure if it's right solution and just bad implementation or it's better to make it in different way. I'll be gratefull for Your help. Team/Models.py roles = (('admin', 'admin'), ('member', 'member'), ('guest', 'guest')) class Team(models.Model): name = models.CharField(max_length=150) description = models.TextField(blank=True) members = models.ManyToManyField(User, through='Membership') cppTables = models.JSONField(default=list, blank=True) def __str__(self): return self.name def get_absolute_url(self): return f'teams/{self.pk}/' def has_user(self, user_id): return self.members.get(pk=user_id).exists() class Membership(models.Model): member = models.ForeignKey(User, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) role = models.CharField(max_length=15, choices=roles, default='member') def __str__(self): return str(self.member) class Meta: unique_together = [['member', 'team']] Team/Decorators.py def required_membership(view_func): def wrapper(request, *args, **kwargs): team_id = kwargs['team_id'] team = Team.objects.get(pk=team_id) if team.has_user(request.user.id): return view_func(request, *args, **kwargs) else: raise HttpResponseForbidden return wrapper Team/Views.py @method_decorator(required_membership, name="dispatch") class TeamDetail(APIView): def get_object(self, pk): try: return Team.objects.get(pk=int(pk)) except Team.DoesNotExist: raise Http404 def get(self, request, pk, format=None): team = self.get_object(pk) serializer = TeamSerializer(team, many=False) return Response(serializer.data) -
multiplication in django in django
how do i multiply two numbers in a budget model for example i want to multiply labour hours and rate per hour ...Then after i add that figure to the total cost of everything ..please help from django.db import models from django.contrib.auth.models import User from .directors import Directors class ApprovedBudget(models.Model): job=models.CharField(max_length=255) time=models.DateTimeField() labourhours=models.IntegerField() rate=models.DecimalField(max_digits=9, decimal_places=2) materials=models.DecimalField(max_digits=9, decimal_places=2) travel=models.DecimalField(max_digits=9, decimal_places=2) other=models.DecimalField(max_digits=9, decimal_places=2) notes=models.CharField(max_length=450) budget=models.DecimalField(max_digits=9, decimal_places=2) actual=models.DecimalField(max_digits=9, decimal_places=2) undercover=models.DecimalField(max_digits=9, decimal_places=2) status = models.CharField(max_length=12,default='pending') #pending,approved,rejected,cancelled is_approved = models.BooleanField(default=False) #hide updated = models.DateTimeField(auto_now=True, auto_now_add=False) created = models.DateTimeField(auto_now=False, auto_now_add=True) objects = Directors() def str(self): return str(self.job) class Meta: verbose_name = (ApprovedBudget) verbose_name_plural = ('ApprovedBudget') @property def labour(self): if(self.labourhours != None ): labour=self.labourhours*self.rate return labour enter code here -
How to create a django queryset object for inner join?
I have two tables. class DibbsSpiderDibbsMatchedProductFieldsDuplicate(models.Model): nsn = models.TextField() nsn2 = models.TextField() cage = models.TextField() part_number = models.TextField() company_name = models.TextField(blank=True, null=True) supplier = models.TextField(db_column='Supplier', blank=True, null=True) # Field name made lowercase. cost = models.CharField(db_column='Cost', max_length=15, blank=True, null=True) # Field name made lowercase. list_price = models.CharField(db_column='List_Price', max_length=15, blank=True, null=True) # Field name made lowercase. gsa_price = models.CharField(db_column='GSA_Price', max_length=15, blank=True, null=True) # Field name made lowercase. hash = models.TextField() nomenclature = models.TextField() technical_documents = models.TextField() solicitation = models.CharField(max_length=32) status = models.CharField(max_length=16) purchase_request = models.TextField() issued = models.DateField() return_by = models.DateField() file = models.TextField() vendor_part_number = models.TextField() manufacturer_name = models.TextField(blank=True, null=True) product_name = models.TextField(blank=True, null=True) unit = models.CharField(max_length=15, blank=True, null=True) class Meta: managed = False db_table = 'dibbs_spider_dibbs_matched_product_fields_duplicate' class DibbsSpiderSolicitation(models.Model): line_items = models.IntegerField() nsn = models.TextField() nomenclature = models.TextField() technical_documents = models.TextField() purchase_request = models.TextField() class Meta: managed = False db_table = 'dibbs_spider_solicitation' What will be the equivalent django query for the inner join of two tables on the column nsn? My views function will be like def inner(request,nsn): obj = ....................... context = {'obj':obj} return render(request,,"a.html",context) the queryset should return the combination of two tables according to the common nsn. -
Django project is corrupted
I have a new project for a little online shop. I use the PyCharm code editor. It saves the progress whenever I switch to a new window and the server autorestarts. After a while of working on the project the server stopped doing that and now it needs to be done manually. When I got to making forms, I noticed that they don't show on the page. It's the same logic as in my previews projects. I made exactly the same forms and models from the old project in the current one and they do not work. Then I did the opposite: I added the models and the form from the current project into the old one and they do render on page. What could be the problem and where shoul I start looking for it? -
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*)
I am trying to run this simple command in Datagrip but this error is showing continuously! Can anyone help me? " You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*) FROM services_receiver' at line 1 " enter image description here -
Convert finished worksheet into io.BytesIO
According to xlsxwriter documentation https://xlsxwriter.readthedocs.io/example_django_simple.html, i can create and write excel-files into django HttpResponse like this: def get(self, request): # Create an in-memory output file for the new workbook. output = io.BytesIO() # Even though the final file will be in memory the module uses temp # files during assembly for efficiency. To avoid this on servers that # don't allow temp files, for example the Google APP Engine, set the # 'in_memory' Workbook() constructor option as shown in the docs. workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet() # Get some data to write to the spreadsheet. data = get_simple_table_data() # Write some test data. for row_num, columns in enumerate(data): for col_num, cell_data in enumerate(columns): worksheet.write(row_num, col_num, cell_data) # Close the workbook before sending the data. workbook.close() # Rewind the buffer. output.seek(0) # Set up the Http response. filename = 'django_simple.xlsx' response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) response['Content-Disposition'] = 'attachment; filename=%s' % filename return response but i want to make code more reusable and testable, so i intented to split this function into 3: def create_worksheet(..) -> xlsxwriter.worksheet.Worksheet pass def convert_worksheet_into_io(worksheet: xlsxwriter.worksheet.Worksheet) -> io.BytesIO: pass def bytesio_to_response(output: io.BytesIO, filename) -> django.http.HttpResponse: response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) response['Content-Disposition'] = f'attachment; filename="{filename}.xlsx"' … -
django-ninja vs djangorestframework
Which of above rest framework do you prefer as of 2022 and django v4? djangorestframework django-ninja I will appreciate if you give me the pros and cons of each for rest-api implementation with django v4. -
I want to disable password in Django's User table
I am currently using django to develop a web app. I want to use an external Idaas and use the uuid issued by the external Idaas as the ID in the User table of django. I don't need the password column in Django at that time, can I disable it? I tried to create a new table without AbstractBaseUser and use the one without the password, but that didn't seem to work with Django's group feature. Therefore. ・Use an external UUID as the key for the Django User table. ・I'm not sure how to do that. ・Use Django's standard group function. I'd like to implement this in a way that satisfies the above three points. If anyone knows more about this, I would appreciate it if you could let me know. Thank you. -
Why am I getting a TemplateDoesNotExist error in Django 4.0 when the template does exist?
I'm new to Django, and I've been struggling with this TemplateDoesNotExist error for a while. I looked at many other users who were having these issues, but none of the proposed solutions seem to work for me. Django cannot find my blog/base.html file and claims it looks in '/home/agile/django_project/blog/templates/blog/base.html' for it, but when I check in my ubuntu, it says the directory exists fine? When I run on my localhost, the site works fine, but when working with ubuntu and Linode is when I run into this problem. Image of Django error Image of the path that exists but Django can't find? Here is my settings.py file, too: Django settings for django_project project. Generated by 'django-admin startproject' using Django 3.2.8. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-e5oqam$0o(1158xprooll%5dg)xk01nw8alh6z1cv@)674^48k' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = … -
Instagram auto refresh the redirect URI which sending oauth2 code
I have pushed my django project onto pythonanywhere, a free hosting website. The code works fine in my local and onto the web as well, but somehow have an issue with instagram authentication. Instagram uses an oauth2 authentication system, in which when the user allows your application, it redirects the user to a specified URI and appends the code inside the URL which further can be used to authenticate the user. Instagram doesn't allow localhosts as valid redirect URL, therefore for the testing I have used something like this InstaAuth.html <script> history.pushState(null, null, '?code=AQD_4...q6#_'); function reloadThePage() { window.location.reload(); } </script> <button type="submit" class="btn btn-primary" onclick="reloadThePage()">Continue</button> which changes the state of the url but doesn't actually refresh it. Then I have button which refresh the current page, which directly trigger below code in my views.py and gets the code through request.GET['code']. Views.py def instaAuth(request): if 'code' in dict(request.GET).keys(): code = request.GET['code'] print('the given code is', code) core = instaCore() user_id, short_lived_access_token = core.code_to_short_access_with_userid(code_string=code) print(user_id) obj = InstaModel.objects.get(username=request.user) obj.instagram_userid = user_id obj.short_lived_access_token = short_lived_access_token obj.is_active = True obj.save() print('all data saved!') messages.success(request, "Your instagram is connected!") return render(request, 'authentication/success.html') return render(request, 'authentication/instaAuth.html') Above code works perfectly fine when I add the code … -
ckeditor not show in my admin panel this contains as a textarea
using the Django framework, add ck-editor in the admin panel, but show textarea I use python manage.py runserver and it works, but it doesn't work when deployed with Apache2. -
getting error while join two serializer in django
serializers.py -while joining HiringstatusSerializer in DriverEditListSerializer getting error class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields = ('id', 'name') class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = ('id', 'name') class HiringstatusSerializer(serializers.ModelSerializer): class Meta: model = Hiring fields = ('driver_id', 'status') class DriverEditListSerializer(serializers.ModelSerializer): city = CitySerializer(read_only=True) location = LocationSerializer() hstatus=HiringstatusSerializer() class Meta: model = Driver fields = ( 'id','employee_id','employer', 'name','uber_name','uber_device_no', 'mobile', 'location', 'city','shift','status', 'aadhar_no','hstatus') views.py class DriverViewSet(viewsets.ModelViewSet): queryset = Driver.objects.filter(is_active=1) serializer_class = DriverEditListSerializer def get_queryset(self): queryset = Driver.objects.filter(is_active=1, city_id=self.request.GET.get('city_id')) return queryset output error this is output error while hit url raise type(exc)(msg) AttributeError: Got AttributeError when attempting to get a value for field `hstatus` on serializer `DriverEditListSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Driver` instance. Original exception text was: 'Driver' object has no attribute 'hstatus'. ERROR "GET /fleet/dt/editdrivers/ HTTP/1.1" 500 187937 -
How to use the attribute : save() in views.py?
** When I use the attribute save() in views.py the page gets this error : NOT NULL constraint failed: pages_login.username def about(request): username = request.POST.get("username") password = request.POST.get("password") data = Login(username=username,password=password) data.save() return render(request, 'pages/about.html') ** -
ValueError at /quiz/None/newquestion Field 'id' expected a number but got 'None'
in my quiz app here is my views.py code def NewQuiz(request): quizForm=forms.QuizForm() if request.method=='POST': quizForm=forms.QuizForm(request.POST) if quizForm.is_valid(): quiz= quizForm.save(commit=False) quiz_id = quiz.id else: print("form is invalid") return redirect('quiz:new-question',quiz_id=quiz_id) return render(request,'quiz/createquiz.html',{'quizForm':quizForm}) #create new question def NewQuestion(request,quiz_id): user = request.user quiz = get_object_or_404(Quizzes, id=quiz_id) questionForm=forms.QuestionForm() if request.method=='POST': questionForm=forms.QuestionForm(request.POST) if questionForm.is_valid(): question=questionForm.save(commit=False) #quiz=models.quiz.objects.get(id=request.POST.get('quizID')) question.quiz=quiz question.save() else: print("form is invalid") return redirect('quiz:new-question',quiz_id=quiz_id) return render(request,'quiz/createqusetion.html',{'questionForm':questionForm}) and here is my urls.py from django.urls import path from . import views app_name="quiz" urlpatterns = [ path('quiz/newquiz', views.NewQuiz, name='new-quiz'), path('quiz/<quiz_id>/newquestion', views.NewQuestion, name='new-question'), path('quiz/<quiz_id>/quizdetail', views.QuizDetail, name='quiz-detail'), path('quiz/<quiz_id>/take', views.TakeQuiz, name='take-quiz'), path('check-marks/<quiz_id>', views.check_marks_view,name='check-marks'), path('quiz/calculate-marks', views.calculate_marks_view,name='calculate-marks'), path('calculate-marks', views.calculate_marks_view,name='calculate-marks'), path('check-marks/<int:pk>', views.check_marks_view,name='check-marks'), ] and i got the above error i tray to change the path to like int:quiz_id but the error is still the same any who can help me please? -
how to fetch only the newest rows from the model in django and show it as a table?
views.py def inventory_display(request): if request.user.vendor == True and request.user.vendor_approval == True: vendor = CustomUser.objects.get(id=request.user.id) vendor_product = vendor.vendor_user.all() items = vendor_product[0].product_variants.all() return render(request, 'vendor/inventory_display.html',{'vendor_product':vendor_product, 'items':items}) Html {% for product in vendor_product %} {% for item in items %} <tr> <th scope="row">{{forloop.counter}}</th> <td>{{product.created|date:"d-m-y"}}</td> <td>{{product.edited|date:"d-m-y"}}</td> <td>{{product.vendoruser}}</td> <td><a href="{% url 'loomerang_admin:product_details' %}">{{product.product_id}}</a></td> <td>{{item.item_num}}</td> <td>{{item.variant_value}}</td> <td>{{item.initial_stock}}</td> <td>2</td> <td>{{item.approval_status}}</td> <td>{{item.approved_date|date:"d-m-y"}}</td> <td>{{product.approved_by}}</td> </tr> {% endfor %} {% endfor %} I am fetching data from 3 different models. I do fetch all the data from these models every time. What if I want to get the newest row only whenever the new row is added? Please, needed help. -
Unable to read Paginator in django template
I am setting up a pagination in my Django APP. Following is my view code: class ClaimsView(ListView): context_object_name = "archives" template_name = "myapp/claims.html" def get_queryset(self, **kwargs): query = self.request.GET.get("q", "") response = self.get_archives(query) paginator =Paginator(response, 4) pages = paginator.get_pages(4) return {'archives': response, 'pages': pages} When I print pages in the viwes file. It give correct result "<page 1 of 1>" but when I am passing it to the HTML file its not give any results there. 'archives' in above dict has a list as value its working fine but not the 'pages' This is how I am reading it in HTML file: {{pages}} -
raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs)) TypeError: 'class Meta' got invalid attribute(s): constraints
#For Battery Manger Project 16-12-2021 class BatteryManager(models.Model): slno = models.AutoField(db_column='Slno', primary_key=True) # Field name made lowercase. lithiumionbattery = models.DecimalField(db_column='LithiumIonBattery', max_digits=18, decimal_places=2, blank=True, null=True) # Field name made lowercase. bty_voltage = models.DecimalField(db_column='Bty_Voltage', max_digits=18, decimal_places=2, blank=True, null=True) # Field name made lowercase. bty_current = models.DecimalField(db_column='Bty_Current', max_digits=18, decimal_places=2, blank=True, null=True) # Field name made lowercase. batterytemp = models.DecimalField(db_column='BatteryTemp', max_digits=18, decimal_places=2, blank=True, null=True) # Field name made lowercase. ambienttemp = models.DecimalField(db_column='AmbientTemp', max_digits=18, decimal_places=2, blank=True, null=True) # Field name made lowercase. bty_username = models.CharField(db_column='Bty_Username', max_length=30, blank=True, null=True) # Field name made lowercase. bty_circlename = models.CharField(db_column='Bty_circlename', max_length=30, blank=True, null=True) # Field name made lowercase. bty_payload = models.CharField(db_column='Bty_payload', max_length=100, blank=True, null=True) # Field name made lowercase. bty_createddate = models.DateTimeField(db_column='Bty_createdDate', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'BatteryManager' def __str__(self): return str(self.Slno)