Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
Django: NoReverseMatch at /shop/stickers/minion-cushion/medida-y-cantidad
I've problems when trying to access to the 2nd part of a 2 Steps form. When clicking on a product, in a given category, for example category 'stickers' and product 'minion-cushion', users are taken to this url: /shop/stickers/minion-cushion/medida-y-cantidad In here they'll find a form 'StepOneForm' that only displays a tamanios (sizes in english) and cantidades (quantities in english) both as forms.ChoiceFields. I'll capture the user's choices for this fields and save the values in the session. And then user should click on Continuar button and should be taken to this url: /shop/stickers/minion-cushion/subir-arte Where users will see the 2nd form "StepTwoForm" and the button to submit the form to DataBase. However, when using this in my StepOneForm template, I get this error: <a href="{% url 'shop:UploadArt' %}" class="btn btn-naranja text-white btn-block">Continuar</a> Error: NoReverseMatch at /shop/stickers/minion-cushion/medida-y-cantidad Reverse for 'UploadArt' with no arguments not found. 1 pattern(s) tried: ['shop\\/(?P<c_slug>[-a-zA-Z0-9_]+)\\/(?P<product_slug>[-a-zA-Z0-9_]+)\\/subir\\-arte$'] But leaving the a tag href attribute blank lets me access this page without problems (except, obviously, I cannot access the the next page when clicking on Continue). <a href="" class="btn btn-naranja text-white btn-block">Continuar</a> Form in template: <form method="post"> {% csrf_token %} <div id="tamanios"> <legend class="text-size20 bold-font"> {{ form.tamanios.label }}</legend> <ul class="form-items"> <li> <span> … -
Django CMS Unknown column 'djangocms_picture_picture.use_responsive_image' in 'field list
Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 233, in inner return view(request, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 34, in _wrapper return bound_func(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/views/decorators/http.py", line 45, in inner return func(request, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 30, in bound_func return func.get(self, type(self))(*args2, **kwargs2) File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 145, in inner return func(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/cms/admin/pageadmin.py", line 1091, in publish_page all_published = page.publish(language) File "/usr/local/lib/python2.7/site-packages/cms/models/pagemodel.py", line 926, in publish self._copy_contents(public_page, language) File "/usr/local/lib/python2.7/site-packages/cms/models/pagemodel.py", line 562, in _copy_contents cleared_placeholders = target._clear_placeholders(language) File "/usr/local/lib/python2.7/site-packages/cms/models/pagemodel.py", line 554, in _clear_placeholders models.query.QuerySet.delete(plugins) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 536, in delete collector.collect(del_query) File "/usr/local/lib/python2.7/site-packages/django/db/models/deletion.py", line 228, in collect elif sub_objs: File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 170, in nonzero return type(self).bool(self) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 166, in bool self._fetch_all() File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 965, in _fetch_all self._result_cache = list(self.iterator()) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 238, in iterator results = compiler.execute_sql() File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/utils.py", line 98, in exit six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return … -
Django nested requests
I have this function whch communicates with SWAPI API and I want to get species name for the movie. So let's say I search 'New Hope', I have to get ['Hutt','Wookiee','Droid','Human','Rodian'] . The problem is that in the SWAPI dict, you don't get the names ,you get a list of urls. "species": [ "https://swapi.co/api/species/5/", "https://swapi.co/api/species/3/", "https://swapi.co/api/species/2/", "https://swapi.co/api/species/1/", "https://swapi.co/api/species/4/" ], This is my conde so far: @api_view(['GET']) def search_films(request,title): context = {} species = [] url = SEARCH_FILM + str(title) if request.method == "GET": r = requests.get(url) if r.status_code == 200: data = r.json() species = data['results'][0]['species'] if species: for species_url in species: get_request = requests.get(species_url) response_data = get_request.json() species.append(response_data) context['species'] = response_data print(context) return Response(data, status=status.HTTP_200_OK) else: return Response({"error": "Request failed"}, status=r.status_code) else: return Response({"error": "Method not allowed"}, status=status.HTTP_400_BAD_REQUEST) At this point I get an error: raise InvalidSchema("No connection adapters were found for '%s'" % url) Any ideas of how to implement this? -
django python migration incorrect .all() results
I am doing a migration of some data but the .all() method is not returning all the results. I have put a raw sql query before the .all() to compare the results and these are not the same. The code is :- def process_trialtypes(apps, schema_editor): """ For each trial make the new prep/flowcell connections based on the trialtype. """ # Test raw data grabbing cursor = django_db.cursor() logger.info('Grabbing trial data') query = """ select * from qc_trials_trial """ cursor.execute(query) for row in cursor.fetchall(): logger.error("RAW: {}".format(row)) # end raw data grabbing Trial = apps.get_model("qc_trials", "Trial") for trial_item in Trial.objects.all(): ttype = trial_item.trialtype_version.trialtype.name logger.error("Processing trial {} of type {}".format(trial_item.name, ttype)) .... class Migration(migrations.Migration): dependencies = [ ('qc_trials', '0023_trial_device_type'), ] operations = [ migrations.RunPython(process_trialtypes), ] ..... If i grep for "LWB" (user noticed problem with this record) in the output from the migration i get - [12/Dec/2018 13:45:34] ERROR [qc_trials.migrations.0024_DATAINT-1708:261] RAW: (22, '2017Dec04-LWB001-01', 4, 1, datetime.datetime(2017, 12, 4, 18, 22, 38, 126411, tzinfo=<UTC>), datetime.datetime(2017, 12, 4, 18, 30, 54, 647303, tzinfo=<UTC>), True, False, 137, 37, 'Mi') - [12/Dec/2018 13:45:34] ERROR [qc_trials.migrations.0024_DATAINT-1708:261] RAW: (252, '2018Feb19-LWB001-02', 6, 1, datetime.datetime(2018, 2, 19, 19, 34, 58, tzinfo=<UTC>), datetime.datetime(2018, 2, 20, 17, 21, 53, tzinfo=<UTC>), True, False, 137, … -
drf serializers.py validated_data doesn't match User's fields AttributeError
DRF user registration module, validated_data contains the data of captcha (validated_data['captcha']='329600'), but the user model does not have the captcha field, so I execute del validated_data['captcha'].The user can be created successfully,but always there is a error: AttributeError: Got AttributeError when attempting to get a value for field `captcha` on serializer `UserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no attribute 'captcha'. user\serializers.py class UserSerializer(serializers.ModelSerializer): captcha = serializers.CharField(max_length=6, min_length=6) class Meta: model = user fields = ('username', 'password', 'email', 'captcha') extra_kwargs = { 'password': {'write_only': True}, 'email': {'required': True}, } def create(self, validated_data): del validated_data['captcha'] return super().create(validated_data) user\models.py class User(AbstractUser): pass I really don't know how to do. -
query to get count, subtotal and total over a date range
Say I have objects with a created_at attribute. I would like to have a query that will result in the counts of created objects on a given date (count_), subtotal of objects up to that date (sub), and the full total of all objects (total_): date | count_ | sub | total_ ------------+--------+-------+------- 2018-10-08 | 1 | 1 | 15 2018-10-11 | 2 | 3 | 15 2018-10-15 | 3 | 6 | 15 2018-10-23 | 4 | 10 | 15 2018-10-24 | 5 | 15 | 15 I managed to get count_ and total_: Obj.objects.annotate( date=Trunc('created_at', 'day', output_field=DateField())i ).values( 'date' ).annotate( count_=Window(expression=Count('id'), partition_by=[F('date')]), total_=Window(expression=Count('id')) ).distinct() generating this SQL: SELECT DISTINCT DATE_TRUNC('day', "obj_obj"."created_at") AS "date", COUNT("obj_obj"."id") OVER (PARTITION BY DATE_TRUNC('day', "obj_obj"."created_at")) AS "count_", COUNT("obj_obj"."id") OVER () AS "total_" FROM "obj_obj"