Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: cannot import name 'routers' from 'rest_framework'
I just started learning the Django REST framework. I'm trying to complete the Quickstart in the official docs. I am getting this error: Exception in thread django-main-thread: Traceback (most recent call last): File "F:\Python\lib\threading.py", line 932, in _bootstrap_inner self.run() File "F:\Python\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "F:\Python\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "F:\Python\lib\site-packages\django\core\management\commands\runserver .py", line 118, in inner_run self.check(display_num_errors=True) File "F:\Python\lib\site-packages\django\core\management\base.py", line 392 , in check all_issues = checks.run_checks( File "F:\Python\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "F:\Python\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "F:\Python\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "F:\Python\lib\site-packages\django\urls\resolvers.py", line 408, in c heck for pattern in self.url_patterns: File "F:\Python\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "F:\Python\lib\site-packages\django\urls\resolvers.py", line 589, in u rl_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_modul e) File "F:\Python\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "F:\Python\lib\site-packages\django\urls\resolvers.py", line 582, in u rlconf_module return import_module(self.urlconf_name) File "F:\Python\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 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File … -
python django queryset merge
I got a problem here and I know you are my saviors... This is the query... flights_table = Flight.objects.values('station__station_name', 'flight_date__month').annotate( flights_number=Count('id')).filter(flight_date__year=datetime.date.today().year).order_by('airline_name') This is the result.. <QuerySet [{'station__station_name': 'ROME', 'flight_date__month': 2, 'flights_number': 1}, {'station__station_name': 'ROME', 'flight_date__month': 2, 'flights_number': 1}]> All I need is to convert the result into this.. [{'station__station_name': 'ROME', 'flights_number' :[0,2,0,0,0,0,0,0,0,0,0,0]}, {'station__station_name': 'PARIS', 'flights_number' :[0,2,0,6,0,12,0,0,0,0,0,0]}] mixing all the 'station__station_name' which has the same name together arranging the list of the values of 'flights_number' based on 'flight_date__month' and months of the year sum 'flights_number' with same 'flight_date__month' and same 'station__station_name' I know it's complicated but I think it's not impossible , I appreciate it -
Run docker with django html button
1-this is my html code <i class="tim-icons icon-laptop" (click)="makeCallToFoo()" style="cursor: pointer; color: #1d8cf8" rel="tooltip" title="View Machine Details"></i>&nbsp;&nbsp; <i class="fa fa-edit" (click)="makeCallToFoo()" style="cursor: pointer; color: #00f2c3" rel="tooltip" title="Write Review"></i>&nbsp;&nbsp; <button onclick="location.href='{% url 'script' %}'" type="button" class="btn btn-danger btn-sm" id="btn2" (click)="changeBtn('btn2')">Off</button> 2- this is urls code path('', views.button), path('output/', views.output, name="script") 3- this is view file def button(request): return render(request, 'home.html') def output(request): data=requests.get("dockerscript/start.py") print(data.text) data=data.text return render(request, 'home.html', {'data':data}) how can i run start.py script through html code that is above -
Django: Database Keys regularly out of sync
I'm running a django app with postgresql in production. I noticed that the database indicies get regularly out of sync after some time, but I couldn't figure out exactly when this happens. Can somebody share a good workflow to find out how this happens or how to prevent this? The customer isn't really happy about this :). I "fixed" it now by running ./manage.py sqlsequencereset every hour by cron and in my deployment script, but this solution looks a bit awkward to me. I use Django 3.1.4 and postgresql 10.14 -
How to get id field from model class in Django using Class-based views
I am using DeleteView in order to allow users to delete their own uploaded images. I want that by clicking on Html link, users will get redirected to the DeleteView confirmation page to delete their images. Problem is that i am getting the next error when trying to display the HTML with the link. Reverse for 'deletegaleria' with arguments '('',)' not found. 1 pattern(s) tried: ['galeria/delete/(? P<pk>[0-9]+)$'] 1.- I know this error is in the template that has the link and it's in this line. <a href="{% url 'deletegaleria' object.id %}"> Sure you want to delete?</a> 2.- If instead i write like this, with the id of the image, i get no error when displaying the HTML <a href="{% url 'deletegaleria' 14 %}"> Sure you want to delete?</a> So in the first example i try to redirect to the url by passing it the id, which was supossedly gotten on the view.py: class imagenDeleteView(DeleteView): model = imagen success_url = reverse_lazy("galeria") def getid(self, request): self.get_object() My urls.py looks like this: urlpatterns = [ path('', views.galeria, name='galeria'), path('delete/<int:pk>', views.imagenDeleteView.as_view(), name='deletegaleria'), ] -
Im trying to get the table from this website and the links of one row [closed]
i need to get all the td texts but find a href get just the link exemple Text result = Text Text2 result = http://test.com import requests import bs4 url = 'https://ticker11.com.br/emissoes/' headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} data_scraped = requests.get(url=url, headers=headers) soup = bs4.BeautifulSoup(data_scraped.text, features='html.parser') data = soup.find('table') soup = bs4.BeautifulSoup(data_scraped.text, 'html.parser') table_andamento = soup.find('table', {'id': 'tablepress-6', }) headers = [heading.text.replace("Fundo", "Fundo") for heading in table_andamento.find_all('th')] removetable = str.maketrans('', '', '@#%-?/()$ ') out_list = [s.translate(removetable) for s in headers] table_rows = [row for row in table_andamento.find_all('tr')] results_andamento = [{out_list[index]: cell.text for index, cell in enumerate(row.find_all("td"))} for row in table_rows] print(results_andamento) -
Error when deplyoing Django-React app to Heroku
I'm deploying my Django-backend, React-frontend app to Heroku and when running git push heroku master I'm running into a weird error: Could not find a required file. Name: index.html Searched in: /tmp/build_7abd977a/public This is my project frontend structure: As you can see the index.html file is there inside the public folder. There is also a build folder that has no public folder inside it but it does also have the same index.html but compressed. Maybe thats the one its looking for? -
Django block page title
I'm trying to create a custom page title for each page but I've not been successfull. The following is the general setup for all my html pages (And what I thought would work; it doesn't) and would appreciate any solutions. head.html something something <title>{% block title %}Default Value{% endblock title %}</title> something something base.html <!DOCTYPE html> <html> {% include "head.html" %} <body> {% include 'header.html' %} {% block content %} {% endblock content %} {% include 'footer.html' %} {% include 'scripts.html' %} </body> </html> 404 html file {% extends 'base.html' %} {% load static %} {% block title %}404{% endblock title %} {% block content %} <div id="main404"> <div class="fof"> <h1>Error 404 :(</h1> </div> </div> {% endblock content %} Currently it still displays the default value indicated in head.html. I would like to customise the page title of each page using the block as attempted above. Thanks. -
JavaScript it's not running in page from a .js file
I have a problem with some scripts of JavaScript. I render on my page some charts from Charts.js, the values for the charts are sent from the backend with some view functions from Django, these function return a JsonResponse, on the urls which are connected with these functions are sending some array which contains a hash-map aka json file that contains the values for the charts fields. With Ajax I take those values from the urls and inject them in JavaScript code that handles the charts rendering. If I put the JavaScript code in a .js file and call the file in HTML it doesn't work, if I put the JS code in a <script> tag it works. How can I put the code into a file? The JS code: // Set new default font family and font color to mimic Bootstrap's default styling Chart.defaults.global.defaultFontFamily = 'Nunito', '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif'; Chart.defaults.global.defaultFontColor = '#858796'; function number_format(number, decimals, dec_point, thousands_sep) { // * example: number_format(1234.56, 2, ',', ' '); // * return: '1 234,56' number = (number + '').replace(',', '').replace(' ', ''); var n = !isFinite(+number) ? 0 : +number, prec = !isFinite(+decimals) ? 0 : Math.abs(decimals), sep = (typeof thousands_sep === … -
Why does it says array.fillter is not a function
I'm making an todolist and each list has checkbox and if user clicks checkbox it calls function below. and when i clicked the checkbox, the console said span.filter is not a function. Please help. It's BOTHERING me. Code: function controlCheck(event) { let ischecked = event.target.checked; const checkobj = { checked: ischecked, }; const span = document.querySelectorAll(".span"); const veryspan = span.filter((e) => e.id === event.target.id); } -
Django how to solve saving empty form problem?
I am trying take 2 different forms in one page in my Django project. They have different form models but they are in the same page and use the same view function. When I try them both of them works, but when I post one of them, the other one is also saving as a empty form. But I do not want this. Why this is happening? views.py def ocr(request, id): .... pdf = get_object_or_404(Pdf, id=id) approval = ApprovalProcess(user_id=request.user, highest_rank=1) #FORM 1 if request.method == 'POST': form = PdfRiskForm(request.POST, request.FILES, instance=pdf) if form.is_valid(): form.save() if pdf.risk_rating == "Low Risk": n = len([x for x in doa_low_list if x < pdf.credit_limit]) approval.highest_rank = n elif pdf.risk_rating == "Medium Risk": n = len([x for x in doa_medium_list if x < pdf.credit_limit]) .... approval.save() else: form = PdfRiskForm() #FORM 2 if request.method == 'POST': form_2 = CommentForm(request.POST or None) if form_2.is_valid(): form_2.instance.comment_other = form.cleaned_data.get("comment_other") form_2.instance.username = request.user form_2.instance.comp_name = userP[0].company form_2.instance.doc_id = pdf if form_2.comment_others is not None: form_2.save() else: form_2 = CommentForm() models.py class PdfRiskForm(forms.ModelForm): risk_rating = forms.ChoiceField(label='Risk Rating', choices=Pdf.RISK_RATING) credit_limit = forms.IntegerField() comments = RichTextField letter_portion = forms.IntegerField(min_value=0, max_value=100, required=False, label="Guarantee Portion (%)") class Meta: model = Pdf fields = ['risk_rating', … -
how to predefine associated model foreign key in django
i created 2 model and both are linked to each other, i created create function view inorder to create the model object. just check my code and read more to know models class group(models.Model): group_name = models.CharField(max_length=100) group_user = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return f'{self.group_name} group' class comments(models.Model): userId = models.AutoField(primary_key=True) name = models.CharField(max_length=100) group = models.ForeignKey(group,on_delete=models.CASCADE,null=True) user = models.ForeignKey(User,on_delete=models.CASCADE) message = models.TextField() date = models.TimeField(auto_now_add=True) def __str__(self): return f'{self.user} comments' views def create(request,pk): if request.method == "POST": name = request.user author = request.user message = request.POST['message'] group = group.objects.GET[pk] message = comments(user=author,message=message,name=name,group=group) message.save() return HttpResponse('') for user i can just type request. user in this case how can auto insert group id from the google adress bar eg: group = self.request['pk'] pls help me in this case -
Dynamically added data not saving into database using django
click here for code Dynamically added value not saving into data base. the value are saved only what we are given first time. and the additional added data not saving into database. -
How to get parameters in django pagination url?
I have a paginator for my category page. everything is working when I enter the URL manually, but I don't know how to get my category name, since my paginator button doesn't show up. I must go to this link with my paginator : http://127.0.0.1:8000/category/category_name/2 but it only works when I enter it in the addressbar. How should I change my URL ? <a href="{% url 'website:category' cat_articles.next_page_number %}"> -
'NoneType' object has no attribute 'views'
I am getting a nontype object error in my views I was adding views functionality to my blog but when I use slugify in my tempate it throws nontype object error My models looks like this class Post(models.Model): sno=models.AutoField(primary_key=True) user=models.ForeignKey(User, on_delete=models.CASCADE, null=True) title=models.CharField(max_length=255) author=models.CharField(max_length=14) slug=models.CharField(max_length=130) views= models.IntegerField(default=0) timeStamp=models.DateTimeField(blank=True) content=models.TextField() and views looks like def blogPost(request, slug): post=Post.objects.filter(slug=slug).first() allPosts= Post.objects.all() post.views= post.views +1 post.save() comments= BlogComment.objects.filter(post=post, parent=None) replies= BlogComment.objects.filter(post=post).exclude(parent=None) replyDict={} for reply in replies: if reply.parent.sno not in replyDict.keys(): replyDict[reply.parent.sno]=[reply] else: replyDict[reply.parent.sno].append(reply) context={'post':post, 'comments': comments, 'allPosts': allPosts, 'user': request.user, 'replyDict': replyDict} return render(request, "blog/blogPost.html", context) and I am getting this error AttributeError at /blog/cyber-security 'NoneType' object has no attribute 'views' Request Method: GET Request URL: http://127.0.0.1:8000/blog/cyber-security Django Version: 3.1.4 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'views' Exception Location: D:\www\allinfo\blog\views.py, line 21, in blogPost Python Executable: D:\www\venv\Scripts\python.exe Python Version: 3.9.0 Please help me out -
Django-Oscar 3.1.6 Frobshop NullBooleanField warning
Following the Frobshop docs, I installed django-oscar v3.0.0, which pulled in django v3.1.6. Every time I run manage.py I get this warning: WARNINGS: catalogue.ProductAttributeValue.value_boolean: (fields.W903) NullBooleanField is deprecated. Support for it (except in historical migrations) will be removed in Django 4.0. HINT: Use BooleanField(null=True) instead. I grepped for NullBooleanField in the Frobshop source, but there were no results. Is there a way to either fix the problem or suppress the message? -
TypeError: create() missing 1 required positional argument: 'validated_data' - django
i have a table that contains many to many and foreign key relation class TableRelation(models.Model): table1 = models.ForeignKey(table1, on_delete=models.CASCADE) table2 = models.ForeignKey(table2, on_delete=models.CASCADE) table3 = models.ManyToManyField(table3) iam using mixins and generic view set for listing and updating. listing retrieve works fine . but when i update or create it shows AssertionError: The .create() method does not support writable nested fields by default. Write an explicit .create() method for serializer table1.serializers.TableRelationSerializer, or set read_only=True on nested serializer fields. so i have written a create methode in the serializer class TableRelationSerializer(serializers.ModelSerializer): table1 = Table1Serializer() table2 = Table2Serializer() table3 = Table3Serializer(many=True) class Meta: model = TableRelation fields = ('id', 'table1', 'table2', 'table3',) def create(self, instance, validated_data): remove_table1 = validated_data.pop('table1',) remove_table2 = remove_role.pop('table2') table_data = remove_permission.pop('table3') table1 = Table1.objects.create(**validated_data) table2 = Table2.objects.create(**validated_data) table3 = Table3.objects.create(**validated_data) TableRelation.objects.create( table1=table1, table2=table2, table3=table3, **table_data) return "fhfh" then iam getting this error TypeError: create() missing 1 required positional argument: 'validated_data' i have tried some other method then also iam getting this error -
Get queryset is showing/saving my model twice because of 'or' statement
I have been using code below in admin.py to show me users that are only in these two groups (test1 and/or test2, user can be in one or both of them in the same time. I want to show in the model only users that are in the group). def get_queryset(self, request): qs = super(PersonUser, self).get_queryset(request) return qs.filter(groups__name='test1') | qs.filter(groups__name='test2') But the problem occurs with the 'or' statement, because when user is in both, then he is shown/saved twice, which is causing a bug. How can I properly change it? -
Show category according to location of a user
I am trying to show categories to a user according to their location. The 'City' is listed in the User Model and 'Category Details' are in a different model called CategoryModel. The added_by field contains the 'email' of the users. How do I query the users model and get the list of all users in that city and filter the list with the category model and get all the categories available under that particular city? Here is the models: class UserList(AbstractUser): UserMiddleName = models.CharField(max_length=100, null=True) usertype = models.ForeignKey(UserType, on_delete=models.CASCADE) Application = models.ForeignKey(AppliationList,on_delete=models.CASCADE, null=True) ContactCell = models.CharField(max_length=100, null=True) City = models.CharField(max_length=30) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [ 'usertype', 'username', 'first_name', 'last_name', ] AbstractUser._meta.get_field('email')._unique = True def __str__(self): return self.email class CategoryList(models.Model): CategoryName = models.CharField(max_length=300) AddedBy = models.ForeignKey(UserList, on_delete=models.CASCADE) AddedDate = models.DateField(auto_now_add=True) UpdatedBy = models.ForeignKey(UserList, related_name="Category_Updated_By", on_delete=models.CASCADE, null=True) UpdatedDate = models.DateField(auto_now_add=True) IsActive = models.BooleanField(default=True) def __str__(self): return self.CategoryName Here is the query I wrote that pulls the list of users from a particular city but how do I modify it to get all the categories listed by these users? USE [testenr] GO CREATE PROCEDURE [dbo].[getCategory] @city varchar(30) = NULL AS SELECT * FROM [dbo].[accounts_userlist] WHERE [City]=@city AND [usertype_id] = 1 GO -
Query a M2M related field in Django
I have a Model Return in my projects like the following: class Kit(models.Model): kit_name = models.CharField(max_length=500, default=0) kit_info = models.CharField(max_length=500, default=0) kit_client = models.ForeignKey(Client, on_delete=models.CASCADE) class ReturnKits(models.Model): kit = models.ForeignKey(Kit, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) items = models.ManyToManyField(ReturnKitsProducts) class Return(models.Model): transaction_date = models.DateTimeField(default=datetime.now) transaction_no = models.IntegerField(default=0, blank=True, null=True) is_delivered = models.BooleanField(default=False) How can I select all the Return objects which contains the kit with kit_client = 4? I know we can query directly related objects using __ but how to query nested ones ? -
Django best practices for testing built-in authentication views
I read somewhere that: In testing a web-application, one should test all aspects of one's own code, but not any libraries or functionality provided as part of Python or Django. Now I'm trying to figure out what this means in regard of the built-in authentication system provided by Django. More precisely, I use the built in authentication system, i.e., urlpatterns = [ path('', include('django.contrib.auth.urls')), ] and now I want to write some tests. First Question: Should I write tests for checking that every url exists and uses the right template for every view? I.e., should I write def test_view_url_exists_at_desired_location(self): response = self.client.get('/login/') self.assertEqual(response.status_code, 200) def test_view_url_accessible_by_name(self): response = self.client.get(reverse('login')) self.assertEqual(response.status_code, 200) def test_view_uses_correct_template(self): response = self.client.get(reverse('login')) self.assertTemplateUsed(response, 'registration/login.html') for all 8 views? I feel like I should test something, but at the same time it feels kind of redundant to test the same thing 8 times. Second Question: I guess I don't have to test the functionality of the views if I use the built in user model, for example, I don't have to test that the login view actually logs-in a user etc. However, I'm using a custom user model (based on AbstractBaseUser) where email is used instead of … -
How I can calculate if time is more than one minute in dajngo?
I am working on django rest APIs where I have to expire a random generated code after one minute. But I am having problem that how I can check weather the time is more than one minute? Thanks in advance for your addition in my knowledge. -
How to fix Django ImageField upload error on admin panel?
I have a model in django named MainPagePicture: class MainPagePicture(models.Model): image = models.ImageField(upload_to='gallery/', null=False) when I try to upload a big image (1 MB and bigger) using admin panel I get this error Error Picture I have no problem with small images (I tried 30 Kb and 16 KB Images) and it works good. my admin.py class is: @admin.register(MainPagePicture) class MainPagePictureAdmin(admin.ModelAdmin): class Meta: model = MainPagePicture my django version is 3.1.6 and pillow version is 8.1.0 and Database is PostgreSQL. -
Django Form is not submitting, after clicking submit it's redirecting to the same page
It's supposed to redirect to detail page after storing the data. However, through Admin it allows to add post. I've checked multiple times views, forms and models there's no error while rendering or after clicking submit button I've also removed the reverse fnc in models and then tried also removed the views fnc but still it doesn't give any errors...I think I made some error in the very beginning. models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse from django.db.models import Max #from ckeditor.fields import RichTextField BU_CHOICES = ( ('Selection','Selection'), ('Discoverability and Availability', 'Discoverability and Availability'), ('Buying Experience' , 'Buying Experience' ), ('Post-Buying Experience','Post-Buying Experience'), ('Flex','Flex'), ) MP_CHOICES = ( ('AE','AE'),('AU','AU'),('BR','BR'),('CA','CA'), ('CN','CN'),('DE','DE'),('ES','FR'),('GB','GB'), ('IN','IN'),('IT','IT'),('JP','JP'),('MX','MX'), ('NL','NL'),('PL','PL'),('SA','SA'),('SE','SE'), ('SG','SG'),('TR','TR'),('US','US') ) FNCT_CHOICES = ( ('NIS','NIS'), ('DR', 'DR'), ('FLEX','FLEX'), ('VSP-SELECTION','VSP-SELECTION'), ('INSTOCK-VCM','INSTOCK-VCM'), ('MARKETING & VENDOR ATTRITION','MARKETING & VENDOR ATTRITION'), ('PROFITABILITY','PROFITABILITY'), ('VCM','VCM'), ('PROGRAM','PROGRAM'), ('TRAINING AND ACES','TRAINING AND ACES'), ('AUTOMATION','AUTOMATION'), ('MIS','MIS'), ('DATA ENGINEERING','DATA ENGINEERING'), ) TASK_CHOICES = ( ('NIS','NIS'), ('DR', 'DR'), ('FLEX','FLEX'), ('VSP-SELECTION','VSP-SELECTION'), ('INSTOCK-VCM','INSTOCK-VCM'), ('MARKETING & VENDOR ATTRITION','MARKETING & VENDOR ATTRITION'), ('PROFITABILITY','PROFITABILITY'), ('VCM','VCM'), ('PROGRAM','PROGRAM'), ('TRAINING AND ACES','TRAINING AND ACES'), ('AUTOMATION','AUTOMATION'), ('MIS','MIS'), ('DATA ENGINEERING','DATA ENGINEERING'), ) NUM_CHOICES =( ('1','1'),('2','2'),('3','3'),('4','4'),('5','5') ,('6','6'),('7','7'),('8','8'),('9','9') ) class Risk(models.Model): id = models.CharField(primary_key=True, editable=False, max_length=10) time = models.DateTimeField(default=timezone.now) header … -
dont work staticfiles on prod (django docker nginx)
heelp!! i containerize my django app, but static filese in debug=false have 404. What i doing incorrectly? django_gunicorn_1 | Not Found: /static/admin/js/nav_sidebar.js django_gunicorn_1 | Not Found: /static/admin/css/base.css etc dockerfile for django FROM python:3.9.0-slim WORKDIR /app COPY ["./commondev", "./requirements.txt", "./entrypoint.sh", "./"] RUN pip install --upgrade pip && pip install -r requirements.txt EXPOSE 8000 ENTRYPOINT ["sh", "./entrypoint.sh"] and for nginx FROM nginx:1.19.0-alpine COPY ./default.conf /etc/nginx/conf.d/default.conf