Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM. Select only duplicated fields from DB
I have table in DB like this: MyTableWithValues id | user(fk to Users) | value(fk to Values) | text | something1 | something2 ... 1 | userobject1 | valueobject1 |asdasdasdasd| 123 | 12321 2 | userobject2 | valueobject50 |QWQWQWQWQWQW| 515 | 5555455 3 | userobject1 | valueobject1 |asdasdasdasd| 12345 | 123213 I need to delete all objects where are repeated fields user, value and text, but save one from them. In this example will be deleted 3rd record. How can I do this, using Django ORM? PS: try this: recs = ( MyTableWithValues.objects .order_by() .annotate(max_id=Max('id'), count_id=Count('user__id')) #.filter(count_id__gt=1) .annotate(count_values=Count('values')) #.filter(count_icd__gt=1) ) ... ... for r in recs: print(r.id, r.count_id, , r.count_values) it prints something like this: 1 1 1 2 1 1 3 1 1 ... Dispite the fact, that in database there are duplicated values. I cant understand, why Count function does not work. Can anybody help me? -
Django 3 Problem with concatenating inside a template tag
I want to concatenate a string inside a template in Django (version 3). I have read everything I could find on the subject and found that this should be the way: {{ "ST" | add: item.id | stringformat:"08d" }} But it produces the error: django.template.exceptions.TemplateSyntaxError: add requires 2 arguments, 1 provided Can anybody shed light into my darkness? -
Django & Certbot - unauthorized, Invalid response (HTTPS)
I'm trying to configure Certbot (Letsencrypt) with Nginx. I get this error : - The following errors were reported by the server: Domain: koomancomputing.com Type: unauthorized Detail: Invalid response from http://koomancomputing.com/.well-known/acme-challenge/xvDuo8MqaKvUhdDMjE3FFbnP1fqbp9R66ah5_uLdaZk [2600:3c03::f03c:92ff:fefb:794b]: "<html>\r\n<head><title>404 Not Found</title></head>\r\n<body bgcolor=\"white\">\r\n<center><h1>404 Not Found</h1></center>\r\n<hr><center>" Domain: www.koomancomputing.com Type: unauthorized Detail: Invalid response from http://www.koomancomputing.com/.well-known/acme-challenge/T8GQaufb9qhKIRAva-_3IPfdu6qsDeN5wQPafS0mKNA [2600:3c03::f03c:92ff:fefb:794b]: "<html>\r\n<head><title>404 Not Found</title></head>\r\n<body bgcolor=\"white\">\r\n<center><h1>404 Not Found</h1></center>\r\n<hr><center>" To fix these errors, please make sure that your domain name was entered correctly and the DNS A/AAAA record(s) for that domain contain(s) the right IP address. - Your account credentials have been saved in your Certbot configuration directory at /etc/letsencrypt. You should make a secure backup of this folder now. This configuration directory will also contain certificates and private keys obtained by Certbot so making regular backups of this folder is ideal. in /etc/nginx/sites-available/koomancomputing : server { listen 80; server_name koomancomputing.com www.koomancomputing.com; location = /favicon.ico { access_log off; log_not_found off; } location /staticfiles/ { root /home/kwaku/koomancomputing; } location /media/ { root /home/kwaku/koomancomputing; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } my DNS A/AAAA records : I didn't know what to do, so I did a search and find django-letsencrypt app, but I don't know hot to use : -
edit a manytomany relation
I have two models in my django app related by manytomany relationship. I created an edit function but it's not working or to be precise it's not able to render the formset Models.py class Player(models.Model): pname = models.CharField(max_length=50) hscore = models.IntegerField() age = models.IntegerField() def __str__(self): return self.pname class Team(models.Model): tname = models.CharField(max_length=100) player= models.ManyToManyField(Player) def __str__(self): return self.tname Forms.py class PlayerForm(forms.ModelForm): class Meta: model = Player fields = '__all__' PlayerFormset= formset_factory(PlayerForm) class TeamForm(forms.ModelForm): player= PlayerFormset() class Meta: model = Team fields = '__all__' exclude = ["player"] Views.py def updateTeam(request,pk): team = Team.objects.get(id=pk) form = TeamForm(instance=team) if request.method == "POST": form = TeamForm(request.POST, instance=team) if form.is_valid(): form.save() context = {'form': form} return render(request, 'packsapp/employee/new.html', context) The above code renders the team name in the form but not the related players. -
Windows equvalent unix command
I got django delete migrations command in reset migration and that is find . -path "*/migrations/*.py" -not -name "__init__.py" -delete find . -path "*/migrations/*.pyc" -delete now need these twos equivalent windows command. -
Multiple file upload in django class based view
In django I have completely used class based view, now I want to allow users to upload multiple files (I have successfully working website to upload one file) In documentation I can find answer for forms from scratch or form model(forms.Model) But not for model forms (models.Model) -
ERRORS: <class 'main.admin.HomePageAdmin'>: (admin.E012) There are duplicate field(s) in 'fieldsets[0][1]'
i'm getting this error when i try to run migrations in my django cartridge ecommerce website: this is my model.py file from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext, ugettext_lazy as _ from django.db import models from mezzanine.pages.models import Page from mezzanine.core.models import Orderable from mezzanine.core.fields import FileField, RichTextField from mezzanine.core.models import SiteRelated from cartridge.shop.models import Product from datetime import datetime from mezzanine.utils.timezone import get_best_local_timezone from mezzanine.conf import settings from pytz import timezone @python_2_unicode_compatible class SiteConfiguration(SiteRelated): """Singleton model for storing site-wide variables.""" logo = FileField("Logo", upload_to="site", format="Image", blank=True) logo_small = FileField( _("Small Logo"), upload_to="site", format="Image", blank=True ) favicon = FileField( _("Favicon"), upload_to="site", blank=True, help_text=_("An image that appears in the browser tab") ) footer_address = RichTextField( default=_("Our address"), help_text=_("Company address displayed in footer.")) footer_subscribe_info = models.CharField( max_length=200, default=_("Pellentesque habitant morbi tristique senectus et netus \ et malesuada fames ac turpis egestas."), help_text=_("Text displayed above the subscription email field.") ) def __str__(self): return str(self.site) class Meta: verbose_name = verbose_name_plural = _("Site Configuration") class Homepage(Page): """Main class for homepage.""" product_heading = models.CharField( max_length=100, default=_("Hot This Week"), help_text=_("A header displayed above the products.") ) second_slider_heading = models.CharField( max_length=100, default=_("GET INSPIRED"), help_text=_("A header displayed above the 2nd slider.") ) second_slider_subheading = … -
How to use get_fields() to access M2M field values
I am using get_fields() to produce a dict of all model field names and values: def get_model_fields(self, obj, fields): model_fields = {} for f in self.model._meta.get_fields(include_hidden=True): value = getattr(obj, f.name) model_fields.append({ 'label': f.verbose_name 'name': f.name, 'help_text': f.help_text, 'value': value, 'class': str(f.__class__)}) This works well except for ManyToMany fields, where the label, name, help_text and class all display fine, but the value returns [modelname].None, despite it containing values. How can I add the values of the ManyToMany field to this function? -
Celery tasks sending to different queues is not working
My use case is to add use multiple queues for different tasks So that all upload_photos task is sent to one queue and upload_phone_number to another queue since upload task is a heavy task, I don't want an upload phone number to be affected by upload_photos, even though I am using different queues, upload_phone_number task is waiting till the execution of upload photos. Is this the right way of writing multiple queues CELERY_QUEUES = ( Queue('fast', Exchange('fast'), routing_key='fast'), Queue('default', Exchange('default'), routing_key='default') ) CELERY_ROUTES = { 'upload_phone_number': { 'exchange': 'fast'` 'exchange_type': 'direct', 'routing_key': 'fast' }, 'upload_photos': { 'exchange': 'default', 'exchange_type': 'direct', 'routing_key': 'default' }, } This is my celery task @app.task(name="upload_phone_number") def upload_photos(): @app.task(name="upload_phone_number") def upload_phone(): -
UNIQUE constraint failed on Posting form
I am trying to post a simle form to create a user. but whenever i try to save the form data it always gives me UNIQUE constraint failed error even if i pass the new mobile number that does not exist on database. ERROR IS: UNIQUE constraint failed: core_user.mobile_no models.py Manager Class is: class UserManager(BaseUserManager): def create_user(self, username, password=None, **extra_fields): """Creates and saves a new user""" if not password: raise ValueError("User must have a password") if not username: raise ValueError("User must have an username") user = self.model(username=username, **extra_fields) user.set_password(password) user.save(using=self.db) return user def create_staff_user(self, username, password=None, **kwargs): user = self.create_user(username, password, is_staff=True, **kwargs) return user def create_super_user(self, username, password=None): user = self.create_user(self, username=username, password=password, is_staff=True, is_super_user=True) return user Model class is: class User(AbstractBaseUser): user_types = ( ("staff", "Staff"), ("super_user", "Super User"), ) first_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) username = models.CharField(max_length=100, unique=True) email = models.EmailField() mobile_no = models.CharField(max_length=10, unique=True) is_active = models.BooleanField(default=True) # can login is_staff = models.BooleanField(default=False) # staff user is_super_user = models.BooleanField(default=False) # super user created_date = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'username' objects = UserManager() # USERNAME_FIELD and password are required by default REQUIRED_FIELDS = [] # e.g full_name def __str__(self): return self.username Views.py class UserCreationView(CreateView): … -
Allow user deletion but keep references to them
What is the standard way of allowing a user to delete their account from your website without removing any references to them, so that others can still see them? For example, how does Stack Overflow do it? I assume that, when you delete your account, your posts and answers aren't deleted as well? So how do they manage it? -
Django signals doesn't work with related name
I am trying to do it when foreignkey changed, but it doesn't work. I want to do something like m2m_changed but for foreign key. User model class User(AbstractUser): balance = models.FloatField(default=0) Transaction model class Transaction(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='transactions') order = models.OneToOneField('Payment.Order', on_delete=models.CASCADE, related_name='transaction') transaction_type = models.CharField(choices=[ ('transfer', 'Transfer'), ('received', 'Received'), ], max_length=20, default='transfer') created = models.DateTimeField(auto_now_add=True) Now I need when new transaction created under the user it collected to the balance. Signals code @receiver(pre_save, sender=User) def collect_transaction(sender, instance, **kwargs): balance = instance.transactions.aggregate(Sum('order__price')) print(balance) but when it work only when i update it from the user not the transaction. For example Transaction.objects.create(user=1, order=1, transaction_type='received') This code won't make the signals work. -
Return File Types in serializer
I have a model which contains array of pdf or image files as many to many field . I want to display the pdf or image in frontend . I want to return the array of files along with the model data in one response. My view now: def AssignmentModuleView(request, assignment_module, path): dict_obj = json.loads(serializers.serialize( 'json', [assignment_module]))[0] dict_obj["details"] = AssignmentModuleHelper( ).get_content(assignment_module) return JsonResponse(dict_obj, status=200, content_type='application/json') Here i could return the json response with the model details , but i cant serialize the files and return the files with content type other than json.How can i accomplish this? -
How can get a queryset and for each object get it queryset
for example I have these models : class Teacher(models.Model): ..... class Student(models.Model): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) ..... Now if I want get a values of teachers I can do it with : Teacher.objects.values("id", "name") but how can I add a queryset of students to the teachers queryset values? Note : I know I can do it by getting students queryset , but in this case I will have many duplicated teachers , so I just want each teacher and his students as array of objects -
Looping through nested dictionary in Django template
My context dictionary for my Django template is something like the following: {'key1':'1', 'key2':'2', 'key3':'3', 'key4':{'key5':{'key6':'6', 'key7':'7', 'key8':'8'}}} I would like to iterate through the dictionary and print something like: some label = 6 some label = 7 some label = 8 How can I achieve this in my Django template? -
Index of row looping over django queryset
I used to convert a django query set to a pandas DataFrame before looping over its rows, but it's not efficient as I loose many properties of a query set. sample_qs = MyModel.objects.all() sample_df = pd.DataFrame(sample_qs) for index, row in sample_df.iterrows(): print(f"Processing row {index} of {sample_df.shape[0]}...") Is there a similar way to iterate over sample_qs without converting it to a pandas DataFrame and still have something similar to index? I know about iterator, but couldn't find anything similar to index: for q in sample_qs.iterator(): print(f"Processing {str(q)}...") -
Add field to the object in the view
I have step form for creating Course object, and inside this object i have tutor field and i want to add something like that Course.tutor.add(request.user) but i can't do that because i haven't any instance to do that class FormWizardView(SessionWizardView): template_name = 'courses/create_course.html' file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT,'courses')) form_list = (CourseForm1,CourseForm2,CourseForm3,CourseForm4) def done(self,form_list,form_dict,**kwargs): instance = Course() for form in form_list: for field, value in form.cleaned_data.items(): setattr(instance, field, value) instance.save() return redirect('courses:my_courses',username=self.request.user.username) -
dkjango ForeignKey that allows Null value
I have class Comment with ForeignKey to self - parent: parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True) I allowed null and blank enteries, but when i try to create a new comment without a parent, i have this log:ERREUR: une valeur NULL viole la contrainte NOT NULL de la colonne « parent_id » can someone help me to resolve this issue -
All mutations must define a mutate method in it - Django
in Django ghaphql in trying use create a new object. But mutation is giving this error - "All mutations must define a mutate method in it" -
How to give all users the ability to view a base data set. And allowing them to add their own data entries to view and share to users
Just a heads up, I am new to using web frameworks. My only experience so far comes from completing the VSCode, Django and Mozilla MDN tutorials. But I'm making my way through these along with my own project. I'm creating a web app that has an "official" database table that all website/app users can view. But, I want to be able to let them add their own data entries to the table, which only they can view and edit. And would be able to grant other users/friends access to their created data entries, to expand the total number of entries made available. Without making everyone using the site having to work out which data entries are the "official" and which are user created. Hopefully a better way of understanding what I'm planning So, what would be the best method for setting up user accounts to have access to the main database table and their own data set, which they can grant access for others to view? Would this mean creating a table for each user, and if so how can this be set up automatically upon account creation? I've read that creating a new table in the database can be … -
Django: Save session variable outside of view is not working
i'm creating my first django project and i'm trying to use session variables out of the view. Firstly i'm getting some data from a form. That works fine. """views.py""" request.session['points_to_victory'] = form.cleaned_data['points_to_victory'] request.session['player_amount'] = form.cleaned_data['player_amount'] request.session['double_out'] = form.cleaned_data['double_out'] request.session['players'] = players request.session['current_player'] = 0 request.session.save() form.process(request.session.session_key) print("Output after form.process: " + str(request.session.items())) But i'm calling a function in my form class and try to add there another entry to my session. The code in the form class is the following: """forms.py""" s = Session.objects.get(pk=session_key) session = s.get_decoded() session["game"] = 1 print("Output in form.prcocess: " + str(session.items())) s.save() The commando line output is: > Output in form.prcocess: dict_items([('points_to_victory', 301), ('player_amount', 1), ('double_out', True), ('players', ['Mustermann']), ('current_player', 0), ('game', 1)]) > Output after form.process: dict_items([('points_to_victory', 301), ('player_amount', 1), ('double_out', True), ('players', ['Mustermann']), ('current_player', 0)]) So the changes in the session dict are done but not saved. Is there any other way to save is? And can you explain why it is not working? -
AWS S3 Bucket Django Image Upload
DONE I am following this guide tho build AWS S3 Bucket in to my Django 3.0 project. I am doing everything as it is in the guide. When I add an image that successfully gets uploaded to the S3 bucket (based on AWS management view where I can see all the stored files) but it does not appear as an image only as a "typical image icon" on the website If I follow the just recently uploaded file's URL in the Google chrome inspector opening the images URL gives me the following message (IDs have been changed fro privacy purposes) ERROR This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>InvalidRequest</Code> <Message> The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256. </Message> <RequestId>862368GFHSD9776868676</RequestId> <HostId> KKjhghfg568fadfgdg768sdg69s8g0s8hsh70hs90h9f0/sdg898= </HostId> </Error> TRIED I have found the same question on aws forum but it has not been answered The solution probably has to to something with Access rights (I don't understand this answer https://stackoverflow.com/a/21614550/10270590 ) "use AWS4-HMAC-SHA256" -
Django-tenant: write dataframe to postgresql schema (automatically find the schema)
Here is my issue in my django app: A tenant log in and then import csv file into his schema. I am processing the with pandas and so I use sqlalchemy to write in the schema. I found help on this topic there SQLAlchemy support of Postgres Schemas but it does not do the trick Here is my django form where the writing operation is happening. the code does not show any error, however, everytime I register a new user, the data gets imported to "t1", the first schema of the list. Strangely enough, if I create a new database and the first user I create is t2, then t2 gets the data imported well, then if i create t1, it gets created well too. But then I create "t3" and the data goes to "t1. my lack of expertise in the topic prevents me from understand what is going and where to look at to find the solution. dbschema = 't1,t2,t3,t4,public' engine = create_engine('postgresql://user:mypassowrd@127.0.0.1:5432/dbexostock12', connect_args={'options': '-csearch_path={}'.format(dbschema)}) DB = tableau.to_sql('dashboard_tableau', engine, if_exists='replace') -
Filtering by nested foreignkey field with django-filters
I've a Customer model which has User as a foreignkey field. In Customer ListView I want to search by name of Customer (Customer --> User --> Name). The ModelChoiceFilter is giving s list of all user objects as a dropdown. I'm unable to figure out how can I put it as a search box of names. Based on another stackoverflow answer, I tried to put it as a ChoiceFilter with a callable as choices argument, but then pagination object started giving error. Could anyone please help. Models.py class User(AbstractUser): name = models.CharField(max_length=100) phone = PhoneNumberField(unique=True) email = models.EmailField(unique=True) class Customer(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) Filters.py class CustomerFilter(django_filters.FilterSet): User = get_user_model() user = django_filters.ModelChoiceFilter(queryset=User.objects.all()) class Meta: model = Customer fields = { 'user':[], } -
Appropriate database for the Django project
We have a new requirement for the Django project. I want to identify the appropriate database for this. Overview: Data will be read from the flat files(Excel, PDF, etc..) and stored into the database. For any future requirement, the stored data from the database will be read again. I go through the Django documentation for the databases and there I see various options (Postgresql, Oracle, MySql, etc..) including 3rd party databases like SQL Server for Django. So, I would like to identify the appropriate database for this application. Which database is better to be used with Django project. Thanks in advance.