Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django:Guide regarding OTP to use in Django app
I am so much confused about OTP function in Django app.help me understand to get it in my project.I searched about many Django_otp ,Twilio etc.But i get confused in all this option.so i want a clear step guide about it. -
Thumbnails wont show up in the table using sorl-thumbnail within if tags
I try to show images as thumbnails with sorl-thumbnail, but they won't show up... If I use the sorl tag outside of the table, withouth the if tags, they will show up, but as shown below, it doesn't. I see some empty images and when I right-click and view the image I get this message: This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>FB1B90D61EDDABFB</RequestId> <HostId>kNOYKLZhcN0N7cgfEfD+bNOs3u4UU2E86gGISMySkNJhobrIA9yFLBh9rgJUbQw+gbyonys5lt8=</HostId> </Error> When I use the {% thumbnail %} tags outside the table/if statement tags, they will show up... I can't find out what might be the cause of this... I work local and have some AWS setup for the live app Here's the code from the template: {% if list.parent.parent_image %} {% if list.image_is_parent %} <td> {% thumbnail list.parent.parent_image "40x40" as im %} <img src="{{ im.url }}"> {% endthumbnail %} </td> {% else %} <td><img src="/media/products/assets/no-image.png" class="img-fluid"></td> {% endif %} {% else %} {% if list.image %} <td> {% thumbnail list.image "40x40" as im2 %} <img src="{{ im2.url }}"> {% endthumbnail %} </td> {% else %} <td><img src="/media/products/assets/no-image.png" class="img-fluid"></td> {% endif %} {% endif %} -
How to return DateTime in different timezone from Django Rest Framework serializer
What is the pythonic way to return DateTimeField of some Django model using an arbitrary timezone in Django Rest Framework? At the moment my view returns DateTime in UTC, because as far as I know Django stores timezone-aware datetimes as datetimes in UTC timezone. Models: class TimezoneMixin(models.Model): TIMEZONES = [(i, i) for i in country_timezones['ru']] timezone = models.CharField(choices=TIMEZONES, ...) class Meta: abstract = True def get_timezone(self): if self.timezone: return timezone(self.timezone) return get_current_timezone() class Organization(TimezoneMixin, models.Model): ... class Event(models.Model): organization = models.ForeignKey(Organization, ...) date_created = models.DateTimeField(auto_now_add=True, ...) ... Serializer: class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('organization', 'date_created', ...) In the ViewSet I populate data as follows organization_id = ... # Some logic to get required organization_id data = { 'date_created': timezone.now(), # django.utils.timezone 'organization': organization_id, ... } serializer = EventSerializer(data=data) if serializer.is_valid(): serializer.save() response_data = serializer.data.copy() # Some logic to rename one of the keys in response data ... return Response(response_data, ...) # rest_framework.response.Response Even if I replace timezone.now() with something like timezone.now().astimezone(organization.get_timezone()) I still receive UTC DateTime in response. Am I correct that it is not a good idea to parse date_created string from response_data, create a DateTime object from it, convert to different timezone and format … -
Django: ModelForm doesn't submmit
I've a 2 steps form. Actually these are 2 forms. The first one lets me capture size and quantity variables from rendered ChoiceFields and save them in session. 2nd Form: renders a FileField and a CharField; and on submit is supposed to retrieve the size and quantity stored in session. So at the end I'm submitting a record of SizeQuantity model with 5 fields: product (ForeignKey to Product model), size, quantity, image (making this optional - null True / blank True to discard its causing any troubles), comment (optional). However, my when I click on the form submit button, on StepTwoForm (2nd form and final) my form doesn't submit -and therefore does not save a record in DB, I don't see any entering by the admin (model is registered). models.py class Category(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) image = models.ImageField(upload_to='category', blank=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def get_url(self): return reverse('shop:products_by_category', args=[self.slug]) def __str__(self): return '{}'.format(self.name) class Product(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='product', blank=True) stock = models.IntegerField() available = models.BooleanField(default=True) created = … -
Django endpoint slow, nested serializer with too many results
I have the following models model_A, model_B, model_c. model_B has a foreign key on model_A model_C has a foreign key on model_B With the below code I am able to get the c__objects from the endpoint /a/<a_id> as a nested property on the list results for the a_id given. Example response { "id": 2, "name": "A record in model C", "email": "example@email.com", "c__objects": [ { "id": 54, . . more-stuff-here . } ], . . . } models.py class model_A(models.Model): name = models.CharField(max_length=200, db_index=True) email = models.EmailField(blank=True) description = models.CharField(max_length=300, null=True, blank=True) class Meta: ordering = ["-id"] def c__objects(self): return C.objects.filter(b__a=self).filter(end_date__gte=now()) class model_B(models.Model): a = models.ForeignKey(A, related_name="a") description = models.CharField(max_length=200) class Meta: ordering = ['-id'] . . . class model_C(models.Model): b = models.ForeignKey(B, related_name="b") description = models.CharField(max_length=2000) end_date = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ['-id'] . . . views.py class A_ViewSet(viewsets.ReadOnlyModelViewSet): def retrieve(self, request, pk=None): queryset = model_A.objects.all() queryset = get_object_or_404(queryset, pk=pk) serializer_context = {'request': request} serializer = A_Details_Serializer(queryset, context=serializer_context) return Response(serializer.data) serializers.py class VenueDetailsSerializer(serializers.ModelSerializer): c__objects = YetAnotherSerializer(many=True) class Meta: model = A fields = ('id', 'name', 'email', 'description', 'c__objects') Now all of these are fine it works when the nested c__objects aren't much, however let's say the c__objects … -
What is the use of Class Meta in django? [duplicate]
This question already has an answer here: How does Django's Meta class work? 4 answers Please explain in easy terms as I have just started to learn django. -
Python to search for complete text in database
Hi guys i'm developing my project and i'm having some trouble. I want my system to search the database for the query; if the input doesnot match with the database then the system should be able to retrieve the correct value of my query. The system is searching The Quran . For example Query:ملكيوم الدين Result:ملك يوم الدين If you guys have any suggestion do let me know what to do currenty i'm using "pyquran" library but unfortunately it doesnot support this feature. -
Using django formset with crispyforms is making pages slow
I was using django formset with crispy forms. The page was opening slow if 1-2 people opens it. But when 100 people try to open the page lots of people couldn't open the page. Formset is defined as below : StudentClassLessonAttendanceFormsetFactory = modelformset_factory(StudentClassLessonAttendance, extra=0, fields=('att', 'student',)) formset = StudentClassLessonAttendanceFormsetFactory(queryset=StudentClassLessonAttendance.objects.filter(semester_id=semester, dateadded=today, lessonhour=hour, cls_id=courseteacherobject['cls_id'], course_id=courseteacherobject['course_id'])) helper = TableInlineHelper() return render(request, 'edit-daily-attendance.html', {'formset': formset, 'helper': helper, 'lessonhour': lessonhour, 'courseclassyear': courseteacherobject['cls__year'], 'courseclassname': courseteacherobject['cls__name']}) After that i stopped using formset and crispy-forms and created the form manually in template. Now the page is opening fast and page can be opened by everybody. The problem is solved but i couldnt figure it out why the page freeze and opens slow when i use formset with crispyforms when the page is called by lots of people at the same time. I am using django 1.9.5 and python 2.7.5 on linux Centos. -
show django-bootstrap modal on any page load
I am trying to use a django-bootstrap4 modal as a nag box to accept a privacy policy. (I have a custom template filter to check whether this has already been accepted. I am not worried about that bit) It should open whenever navigating to a new page. I have tried this solution, but the modal is not dismissable, not even with a close button. Neither does it shadow the page behind it. I have imported the custom css using <link href="/static/css/auto_modal.css" rel="stylesheet">, is this correct when using django-bootstrap? The code for the modal is in the base.html template. Is it possible to take it into a seperate template just for the modal? -
Docker django mysql.sock in different location
I'm trying to containerize my django file, and I keep running into the issue:(2006, ’Can\‘t connect to local MySQL server through socket \‘/var/run/mysqld/mysqld.sock\’ (2 “No such file or directory”) I found out later mysql.sock is in this location:/tmp/mysql.sock instead of /var/run/mysqld/mysqld.sock, how do I change the location for docker to see /tmp/mysql.sock Here is my docker-composr.yml: version: '3' services: db: image: mysql command: --default-authentication-plugin=mysql_native_password restart: always environment: MYSQL_ROOT_PASSWORD: somepassword adminer: image: adminer restart: always ports: - 8080:8080 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db I have followed the instructions on the mysql docker website to link mysql instance to a container -
Issue with Django Forms saving data
I am trying to make a Django web application which saves information about a User and his Hobbies to a local database. For some reason it isn't working and I am having trouble figuring out the issue. Here is my code: The models.py file: my_choices = ( (0, "None"), (1, "Football"), (2, "Cricket"), (3, "Swimming"), (4, "Cycling"), ) class Hobby(models.Model): user = models.ForeignKey(Profile, on_delete=models.DO_NOTHING) field = models.IntegerField(choices=my_choices, default=0) The views.py function for Profile: def profile(request,user): try: profile_object = Profile.objects.get(id=user) if request.method.POST: form = HobbyForm(request.POST) if form.is_valid(): profile_object.field = form.cleaned_data["field"] profile_object.save() context = { "form": form, "profile": profile_object, } return render(request, 'mainapp/profile.html', context) else: context = { "form": form, "profile": profile_object, } return render(request, 'mainapp/profile.html', context) else: context = { "form": form, "profile": profile_object, } return render(request, 'mainapp/profile.html', context) except Profile.DoesNotExist: context = { "form": form, "profile": profile_object, } return render(request, 'mainapp/profile.html', context) The forms.py code for the actual form: class HobbyForm(ModelForm): class Meta: model = Hobby fields = ["field"] And the profile.html page: <form action="myurl/{{profile.id}}/" method="post"> {% csrf_token %} {% form.as_p %} <input type="submit" value="OK"> </form> When I run this code, I get the following error: TypeError at /profile/ int() argument must be a string, a bytes-like object or a … -
python/django inheritance issue
I am having an issue with python 3 and django class inheritance function overriding. My classes look something like this. class A(GenericAPIView): def _post(self, request, pk=None, *args, **kwargs): raise NotImplementedError def _put(self, request, pk=None, *args, **kwargs): raise NotImplementedError def _get(self, request, pk=None, *args, **kwargs): raise NotImplementedError def post(self, request, pk=None, *args, **kwargs): try: return self._post(request, pk=pk, *args, **kwargs) except ChunkedUploadError as error: return Response(error.data, status=error.status_code) def put(self, request, pk=None, *args, **kwargs): try: return self._put(request, pk=pk, *args, **kwargs) except ChunkedUploadError as error: return Response(error.data, status=error.status_code) class B(A): def _put(self, request, pk=None, *args, **kwargs): finalized = self.finalize(pk, request, *args, **kwargs) print('do put stuff here') return (finalized) def _post(self, request, pk=None, *args, **kwargs): finalized = self.finalize(pk, request, *args, **kwargs) print('do post stuff here') return (finalized) def finalize(pk, request, *args, **kwargs): return('placeholder for finalize stuff') class C(B): def finalize(pk, request, *args, **kwargs): return('doing my special finalize stuff here') c_put = C.put(pk, request, *args, **kwargs) If i print c_put I get "doing my special finalize stuff here" c_post = C.post(pk, request, *args, **kwargs) If i print c_post I get "placeholder for finalize stuff" What is happening is I cannot override the finalize function if post is called. If I make a put request to my … -
Is it possible to embed a Python/Django app in a Java Web App?
I have a java web application running on Apache Tomcat and a django application. They both interact with the same database(levelDB).Since they are two different processes, they both can't interact with database at the same time. My preferred solution, is to have the django app embedded in the Java app(main application) so that interacting with the database can be synchronised. -
Django: NOT NULL constraint failed: shop_tamanioscantidades.producto_id
I've a form that's giving me this error on submission: IntegrityError at /shop/stickers/minion-cushion/subir-arte NOT NULL constraint failed: shop_tamanioscantidades.producto_id My model TamaniosCantidades makes a referece to Product model with a foreign key, because I need to store each record of TamaniosCantidades with a reference to wich product the form was submitted. Why? model: class Category(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) image = models.ImageField(upload_to='category', blank=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def get_url(self): return reverse('shop:products_by_category', args=[self.slug]) def __str__(self): return '{}'.format(self.name) class Product(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='product', blank=True) stock = models.IntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) verbose_name = 'product' verbose_name_plural = 'products' def get_url(self): return reverse('shop:ProdCatDetail', args=[self.category.slug, self.slug]) def __str__(self): return '{}'.format(self.name) class TamaniosCantidades(models.Model): # usuario = models.ForeignKey(User, on_delete=models.DO_NOTHING) producto = models.ForeignKey(Product, on_delete=models.CASCADE) tamanios = models.CharField(max_length=10, choices=TAMANIOS) cantidades = models.CharField(max_length=10, choices=CANTIDADES) imagenes = models.FileField(upload_to='imagenes/', null=True, blank=True) # imagenes = models.ImageField(upload_to='category', blank=True) instrucciones = models.CharField(max_length=200, blank=True, null=True, default='') uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tamanios template: {% extends 'base.html' %} {% load static %} {% load … -
Order By with Foreign Object Field if it exists
I am trying to do a query where I would order by foreign object if there is one - or by a local field. Example: class AuditorData(Base): auditor_weight = models.FloatField() audited_object = models.ForeignKey('MyObject', related_name='audits') class MyObject(Base): weight = models.FloatField() Basically I want to do order by Max(audits.auditor_weight) but if there is no audits, it will order by 'weight' How could I create a query to do so I tried to do use annotation and aggregation, with coalesce order_by, but it doesn't work. Any solution? -
Django OneToOneField with db_index=False vs OneToOneField
As I know OneToOneField will create a unique-constraint and database will create unique-index to manage uniques value for the unique-constraint internally. As the result, unique-constraint would be equivalent with unique-index. (because both have a unique-index table) What if models.OneToOneField('one_to_one', db_index=False)? OneToOneField needs unique-index to manage unique-constraint but It tells not to create db_index. It seems weird but there isn't any syntax error. How does it work? How is it different between models.OneToOneField('one_to_one', db_index=False) and models.OneToOneField('one_to_one')? -
django admin list_display with count annotation
I'd like to add "annotation count" field into list_display in Django Admin. models.py class Log(models.Model): ... ip_address = models.GenericIPAddressField( verbose_name=_('IP address'), db_index=True, ) ... admin.py class LogAdmin(admin.ModelAdmin): list_display = (..., 'ip_address', 'ip_address_count', ...) def ip_address_count(self, instance): return models.Log.objects \ .filter(ip_address=instance.ip_address) \ .count() ip_address_count.short_description = _('IP Address Count') It works fine with "LOTS OF" SQL queries. I'd like to improve my admin.py like this: class Log(models.Model): ... def get_queryset(self, request): qs = super(LogAdmin, self).get_queryset(request) qs = qs.values('ip_address') \ .annotate(ip_address_count=Count('ip_address')) return qs def ip_address_count(self, instance): return instance.ip_address_count However, I encountered the error messages: 'dict' object has no attribute '_meta' It seems that I found the reason why the error occurs: Django Admin, can't groupe by: Exception Value: 'dict' object has no attribute '_meta' However, it does not help me to solve the problem. Thank you for your answers. -
'set' object is not reversible
i am new to django, so i am following a tutorial online. however when i got to named url, i started having the following errors which i can't seem to find my way around even after checking for solutions online. I am trying to use named url in a html template (article_list.html) so when users clicks on any of the articles, it takes them there to read about such article. Here is my trackback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/articles/ Django Version: 2.1.4 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'articles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\BOLADE\Desktop\django-playlist\blog\templates\base_layout.html, error at line 0 'set' object is not reversible 1 : {% load static from staticfiles %} 2 : <!DOCTYPE html> 3 : <html lang="en"> 4 : <head> 5 : <meta charset="UTF-8"> 6 : <title>Articles</title> 7 : <link rel="stylesheet" href="{% static 'styles.css' %}"> 8 : </head> 9 : <body> 10 : Traceback: File "C:\Users\BOLADE\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\BOLADE\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\BOLADE\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\BOLADE\Desktop\django-playlist\blog\articles\views.py" in article_list 9. return render(request, 'articles/article_list.html', {'articles': articles}) File … -
Django best way to share same user model and database between multiple projects
I have multiple Django projects. Each one has its own installed apps. They do not have the same apps installed. The thing in common between them all, is that they should use and share the same Custom User model and database. Which is the right way to accomplish this? Thanks! -
How to identify css inline attribute
In the webpage that I'm scraping, there are a lot of titles and I need to identify them to set one value in my database. The problem is that those titles doesn't have a specific ID or Class. They follow those pattern: <p ALIGN="CENTER"><font face="Arial" SIZE="2"> <a name="tituloivcapituloisecaoii"></a><b> <span style="text-transform: uppercase">Seção II<br> DAS ATRIBUIÇÕES DO CONGRESSO NACIONAL</span></b></font></p> <p ALIGN="CENTER"><font face="Arial" SIZE="2"><a name="tituloivcapituloisecaoiii"></a> <b><span style="text-transform: uppercase">Seção III<br> DA CÂMARA DOS DEPUTADOS</span></b></font></p> One attribute that identifies them is: text-trasform: uppercase. How can I check if the p contains one title? -
How to make a few button or div make move beside each other with bootstrap or css
How to make a few button or div make move beside each other with bootstrap or css? Is it possible? or I should use javascipt? Is it possible by Django templates? thanks, Saeed -
Return to URL if theres an error in django signal
I have a field called keyChecker in mt tithe model. KeyChecker is unique and is only generated after a form is submitted (via pre_save signal).Now the issue is that everything saves when the key doesnt exist but when the key exists it throws an IntegrityError, which is expected. However I want to redirect users to a url whenever this error is thrown. Models.py class Tithe(models.Model): YEAR = [] for r in range((datetime.datetime.now().year), (datetime.datetime.now().year+10)): YEAR.append((r,r)) MONTHS = ( ('January', 'January'), ('February', 'February'), ('March', 'March'), ('April', 'April'), ('May', 'May'), ('June', 'June'), ('July', 'July'), ('August', 'August'), ('September', 'September'), ('October', 'October'), ('November', 'November'), ('December', 'December'), ) year = models.IntegerField( choices=YEAR, default=datetime.datetime.now().year) month = models.CharField(max_length = 50, choices = MONTHS, null=True, blank=True) week1 = models.DecimalField(max_digits=10, decimal_places=2, default = 0) week2 = models.DecimalField(max_digits=10, decimal_places=2, default = 0) week3 = models.DecimalField(max_digits=10, decimal_places=2, default = 0) week4 = models.DecimalField(max_digits=10, decimal_places=2, default = 0) total = models.DecimalField(max_digits=10, decimal_places=2, default = 0) keyChecker = models.CharField(max_length=500,unique=True, null=True, blank=True) member = models.ForeignKey('Member', on_delete = models.CASCADE) def __str__(self): return "{0}_{1}_{2}".format(self.member, self.year, self.month) def get_absolute_url(self): return reverse('tithe', kwargs={'slug': datetime.datetime.now().year, 'slug2':datetime.datetime.now().month}) def get_key_checker(instance, new_slug = None): memberpk = instance.member_id member = Member.objects.get(pk = memberpk) fname = member.fname lname = member.lname contact = member.contact year = … -
Why selectable list of items doesn't work in Django?
The jdango view returns list of components and the li items contain html code saved in {{ component.html }} variable. html file: <ol id="app_components"> {% for component in components %} <li id="{{ component.id }}" class="component"> {{ component.html|safe }} </li> {% endfor %} </ol> js file: $( "#app_components" ).selectable(); css file: .ui-selecting { background: grey; } .ui-selected { background: blue; } I don't know why not works. Any idea ? Thanks. -
Django: Fetching value of field for an object in for loop
Suppose I have a model named Visitor. models.py class Visitor(models.Model): name = models.CharField(max_length=100,primary_key=True) region = models.CharField(max_length=100) city = models.CharField(max_length=100) country = models.CharField(max_length=100) Now what i need to is the following thing views.py myView(request): o = Visitor.objects.get(name='Ankit') FList = ['region','city','country'] #flist is the list of fields for myField in FList: print(o.myField) 'I want to print value of each field for this particular object 'o'.' I know print(o.myField) is completely incorrect because it will simply try to fetch value of 'myField' field for this particular object from Visitor model and 'myField' field doesn't exist in this model. How can i achieve this? Thanks in advance. -
Django/taggit-can't add new tag while overwriting safe() in models
I was trying to overwrite safe() and give "card" that don't have tag a unified tag "uncategorized", but the code at the last three line which works fine in shell, can't save tag "uncategorized" in practice. class Card(models.Model): """A card the user adds""" title=models.CharField(max_length=30,blank=True) #editable=False-disabled field slug, otherwise it would show as an input choice slug=models.SlugField(max_length=30,editable=False) content=models.CharField(max_length=140) tags=TaggableManager(blank=True) date_added=models.DateTimeField(auto_now=True) def __str__(self): #"""Return a string representation of the model""" return self.content[:50]+"..." def save(self,*args,**kwargs): if not self.title: self.title=self.content[:10] self.slug=slugify(self.title) super().save(*args,**kwargs) if not self.tags.names(): self.tags.add("uncategorized") super().save(*args,**kwargs)