Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i grouping django table
I have an app named Post and my models.py for the app have more than 10 tables/class. Under my admin.py My question is; how can i gruoping these tables I want like this for example; posts -Gönderiler -Kategori listesi -Tag listesi Games -Game maps -Matchs -Oyuncu Games1 -League of legends game... -
Django Login will Authenticate but redirect fails only on remote server
I have just finished building my web app and migrated it to a digital ocean droplet. The problem that I am having is I can run runserver 0.0.0.0:8000 and use my server ip to get to my homepage, landing-page, signup etc. As well I am able enter incorrect credentials and be redirected back to sign-in again. As soon as the correct credentials are entered Django hangs up until I stop the server. On my local machine I do not have this problem, as well by connecting through LAN I am able to login successfully. My local machine connects to a database on a droplet in the same datacenter as my Django prod server. Strangely, According to my database the attempt to login is successful. The issue seems to be something related to redirecting to my view. by changing the redirect to my landing page and adding print statements to my view I can see that it is never accessed following authentication. Mysql version is identical across both instances. From my Django Instance: I can login to the database from my instance I can create a new SuperUser from my instance manage.py shell I can fill out the signup form and … -
Django Basic Auth
I have two serializers... MyRegisterSerializer inherits and extends a popular app/package, django-rest-auth, which connects to a fairly standard user table. I also have a Model and serializer for a custom app, TeamSerializer (a one-to-many relationship with users). When a user signs up, I would like them to be able to join a team at the same time, so I somehow need to create a team, return the team ID and then pass that ID to the RegisterSerializer, so that the ID of the team can be stored in the User table. I know I could make two calls, first to create the team and return the value, and then pass it to the register serializer, but is there a way to do this all in one serializer? I am a n00b at python, and cant find a great example of this, considering I have to return the get_cleaned_data() function as it is. Thank you! class TeamSerializer(serializers.ModelSerializer): class Meta: model = Team fields = ('id', 'name', 'logo', 'user') class MyRegisterSerializer(RegisterSerializer): first_name = serializers.CharField() last_name = serializers.CharField() def get_cleaned_data(self): super(MyRegisterSerializer, self).get_cleaned_data() return { 'team_id': <How do I get this value> 'username': self.validated_data.get('username', ''), 'position': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), 'first_name': self.validated_data.get('first_name', ''), … -
How to add static file in django before pushing
I'm coding css and javascript file for my web project. That files I put in app folder. I use "git add ." and "git push origin +(branch_name)", but I clone project again, I don't call that static files I wrote. How do I solve problem? -
How to make a loop in views.py in django
I don't want to repeat Destination function again and again in separate variables. I tried to make different variables and equaled them to Destination() but it didn't work. How to make a loop in it so that I don't have to repeat it? def index(request): dest1 = Destination() dest1.desc = 'Hello, How are you?' dest1.img = '01.jpg' dest2 = Destination() dest2.desc = 'Hello, HOw are you?' dest2.img = '02.jpg' context = { 'dests1': dests1, 'dests2': dests2, 'dests3': dests3 } return render(request, 'index.html',context) -
Importing a .xlsx file into models, receiving an Integer out of range error for the DateField: Line number: 1 - integer out of range
I am attempting to import a spreadsheet of video games into my django database. I have set up the models with date fields, and I believe I have formatted my spreadsheet so that it matches with what Django is expecting. I am using the django import-export package. I have tried to manually set the formatting in the django settings.py file, but that doesn't seem to fix it. models.py releaseDateJP = models.DateField(null=True,blank=True) releaseDatePAL = models.DateField(null=True,blank=True) releaseDateNA = models.DateField(null=True,blank=True) settings.py DATE_INPUT_FORMATS = ['%Y-%m-%d'] Here is what the first line of my spreadsheet looks like: I expect for my models to be filled with the appropriate data; the release dates. But the first date field (releaseDateJP), is what I believe to be causing the error:Line number: 1 - integer out of range -
Django count all child models from parent in one query
I'm trying to count all children from my parent model but I cannot make It work. See below for my model and things that I have tried. Model class ParentXX(models.Model): created = models.DateTimeField(auto_now_add=True, null=True) last_updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=200,null=False,blank=False,unique=True) class ChildrenXX(models.Model): created = models.DateTimeField(auto_now_add=True, null=True) last_updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=200,null=False,blank=False,unique=True) parent_sample = models.ForeignKey(ParentXX, models.CASCADE, blank=False, null=False, related_name='child_sample') Code cnt = ParentXX.objects.filter(name="xx").annotate(c_count=Count('child_sample')) #Not working cnt = ParentXX.objects.filter(name="xx").annotate(c_count=Count('parent_sample')) #Not working print(c_count) -
Uninstalling django-tinymce. Import error when makemigrations
Thanks for taking the time to read this. I was not happy with TinyMCE extension in django and decided to switch to django-summernote. I first ran pip uninstall django-tinymce Removed all mentions of tinymce in the actual project. Followed the instruction to install django-summernote. Upon completion I decided to run python manage.py makemigrations python manage.py migrate to apply new extension, but get an error: File "/Users/rasulkireev/Sites/dj-pw/now/migrations/0006_auto_20190703_0134.py", line 4, in <module> import tinymce.models ModuleNotFoundError: No module named 'tinymce' I'm not sure why would Django care about what I did previously since I am simply asking to replace the editor. I can't run python manage.py runserver either. I can't do anything before fixing this. I beg you guys, please help. Note: I would ideally want to keep the contents of my current database. Thanks for taking the time to read this. -
How to link AbstractUser to Group and query in Views for Business Logic
I have limited the amount of files a user can upload to my site using a logical query in my upload app's views.py file. Long story short, after the user has uploaded 5 files, they are redirected to a page that says they must become a premium member. I am now trying to add to that logic by checking if they are in the "Free User" group. If they are not, they should be allowed to upload an unlimited number of files. So far I have used the admin panel to create two groups. One is "Free User" and one is "Gold User". I gave both groups add, change, delete, view permissions for my "beatupload" app. I added this code to my users models.py # users/models.py from django.contrib.auth.models import AbstractUser, Group from django.db import models class CustomUser(AbstractUser): pass # add additional fields in here group = models.ForeignKey(Group, on_delete=models.CASCADE, default=1) def __str__(self): return self.email I see that I have a field in my users_customuser table for group_id, but when I change the group in the admin interface no changes reflect. When I check the table using select * from auth_group I see that I have id and group name, being Free … -
How to copy image to a new variable
I'm trying this code, but I'm doing something wrong. class Photo(TimestampedModel): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to="photos") image_card = models.ImageField(upload_to="photos", null=True) def save(self, *args, **kwargs): if not self.id: self.image = self.compressImage(self.image) self.image_card = self.resizeImage(self.image) super(Photo, self).save(*args, **kwargs) The idea is to create a second image (image_card), with a new size. In the end, I get an image for image_card but not for image. The methods compressImage() and resizeImage() works correctly, but I suspect that resizeImage is getting the same image instance. If I comment the line self.image_card = self.resizeImage(self.image) , image works again. -
How to use models variable as url?
In my models.py file i made a variable called hero_name. For instance, if the hero name is Bart, I want the url to be ./heroes/Bart urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:hero_name>/', views.heropage, name='heropage'), ] views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from .models import Heroes def index(request): return render(request, 'heroes/index.html') def heropage(request, hero_name): get_object_or_404(Heroes, pk=hero_name) return render(request, 'heroes/heropage.html') models.py from django.db import models class Heroes(models.Model): hero_name = models.CharField(max_length=200) -
How to fix "Error Removing corrupted schedule file 'celerybeat-schedule': error('Bad magic number',)r"
I can run the celery beat normally using the command in the terminal, but when I go to run in aws, I get the following error: [2019-07-10 11:30:35,166: ERROR/MainProcess] Removing corrupted schedule file 'celerybeat-schedule': error('Bad magic number',) Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.6/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'scheduler' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/beat.py", line 476, in setup_schedule self._store = self._open_schedule() File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/beat.py", line 466, in _open_schedule return self.persistence.open(self.schedule_filename, writeback=True) File "/usr/lib64/python3.6/shelve.py", line 243, in open return DbfilenameShelf(filename, flag, protocol, writeback) File "/usr/lib64/python3.6/shelve.py", line 227, in __init__ Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback) File "/usr/lib64/python3.6/dbm/__init__.py", line 94, in open return mod.open(file, flag, mode) _gdbm.error: Bad magic number Could someone please help me to understand whats's wrong? -
How to decode utf-8 encoded string in python 3?
I have the following situation: encoded_string = str('дис'.encode('utf-8')) I need to convert this to string because django's set_cookie() takes a string and I can't seem to be able to write the function f for which: f(encoded_string) == 'дис' is again. If I don't convert this string then django returns Internal server error. Can you please help? -
Serializers crash when return an instance
I am trying to add a new variable in my endpoint. Before I used cliente, but now I want to add user (for finding the cliente). The problem is that user is not in my Pedido model, so I add using user = serializers.IntegerField(). I can use it in the method without a problem, but when return the instance pedido, something is wrong. serializers.py class PedidoWriterSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() lineas = DetallePedidoSimpleSerializer(many=True, required=False) class Meta: model = Pedido exclude = ('monto','entrega_realizada','pedido_confirmado', 'cliente',) extra_kwargs = { 'user': {'write_only': True} } def create(self, validated_data): if 'lineas' in validated_data: lineas = validated_data.pop('lineas') if 'entrega_solicitada' in validated_data: entregas_solicitadas = validated_data.pop('entrega_solicitada') user = self._kwargs.get('data').get('user') bandera = True c = Cliente.objects.get(usuario_id=user) validated_data['cliente'] = c if (not c.habilitado): bandera = False if bandera: total = 0 for l in lineas: print(2) print(l) p = Producto.objects.get(pk=l['producto'].id) if ((not p.activo) or (not p.stock) or (not(l['cantidad']>0 and l['cantidad'] <1000))): bandera = False else: today = datetime.now() prom = p.ofertas.filter(activa=True, desde__lte=today, hasta__gte=today).last() if prom: monto_descuento = (p.precio * prom.descuento) / 100 total = (p.precio - monto_descuento) * l['cantidad']\ + \ total else: total = p.precio * l['cantidad'] + total if total < c.ciudad.monto_minimo: bandera = False if bandera: for e in … -
How to add linkable text in django 2.2 blog post from admin panel
class BlogPost(models.Model): # blogpost_set -> queryset # id = models.IntegerField() # pk user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) image = models.ImageField(upload_to='image/', blank=True, null=True) title = models.CharField(max_length=120) slug = models.SlugField(unique=True) # hello world -> hello-world content = models.TextField(null=True, blank=True) publish_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = BlogPostManager() class Meta: ordering = ['-publish_date', '-updated', '-timestamp'] def get_absolute_url(self): return f"/blog/{self.slug}" def get_edit_url(self): return f"{self.get_absolute_url()}/edit" def get_delete_url(self): return f"{self.get_absolute_url()}/delete" def show_url(self, obj): return format_html("<a href='http://pre.com{0}'>{0}</a>", obj.url) -
Why is my queryset only returning particular properties of my model instance in 'get' request?
Using django 1.11, I have a model with particular properties that I want to return with a get request(in my case get_queryset is returning a response to the get request), and it's only returning particular properties of a given model instance(a.k.a. object, a.k.a. record). I want all the properties of the record, not just the ones django decides by default to give me using a queryset. I've tried using the 'ekg.objects.all().filter(user=request.user).values('user', 'id') to try to get particular values returned from the database to no avail. class Ekg(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank = False, null=False) ekgId = models.AutoField(primary_key=True) sampling_rate = models.DecimalField(max_digits=5, decimal_places=2, null = False, blank = False) dataTag2 = models.TextField(null = False, blank= False) dataTag3 = models.TextField(null = False, blank= False) timestamp = models.DateTimeField(auto_now_add=True, null=False, blank=False) #date and time of the signal added to db ''' ''' class EkgAPIView(mixins.CreateModelMixin, generics.ListAPIView): permission_classes= [permissions.IsAuthenticated] authentication_classes= [JSONWebTokenAuthentication] serializer_class = EkgSerializer def get_queryset(self): #return all qs = Ekg.objects.all().filter(user=request.user).filter(ekgId=2).values('user', 'ekgId', 'sampling_rate', 'dataTag2', 'dataTag3', 'timestamp') return qs output using api endpoint(not desired) [{"sampling_rate":"212.00","dataTag2":"anotherDatatag2","dataTag3":"anotherDatatag3"}] expected (timestamp not exactly that format, but sending me back something [{"ekgId ":"2", "timestamp":"July 10, 2019 - 22:19:47","sampling_rate":"212.00","dataTag2":"anotherDatatag2","dataTag3":"anotherDatatag3"}] -
Math expression in html format
My study shows the only effective method to include the mathematical expression on my html pages is mathType. It converts the math expression to html code. That is not supported in some of the browsers (including chrome) however. Is there any alternative? -
Django: How to pass value from one CBV to another
I'm trying to customize django authentications forms/templates. URL /accounts/password_reset/ (CBV:PasswordResetView) is used to enter account email. After form submitting user redirected to /accounts/password_reset/done/ (CBV:PasswordResetDoneView) I need to use email value in PasswordResetDoneView. How can I do it? Sorry for newbie question. urls.py from django.urls import path, include from . import views urlpatterns = [ # ... path('accounts/password_reset/', views.CustomPasswordReset.as_view(), name='password_reset'), path('accounts/password_reset/done/', views.CustomPasswordResetDone.as_view(), name='password_reset_done'), # ... ] views.py from django.contrib.auth import views as auth_views from .forms import LoginForm, ResetForm, NewPasswordForm class CustomPasswordReset(auth_views.PasswordResetView): template_name = 'authorization/password_reset_form.html' html_email_template_name = 'authorization/password_reset_email_html.html' email_template_name = 'authorization/password_reset_email_plain.html' subject_template_name = 'authorization/password_reset_subject.txt' class CustomPasswordResetDone(auth_views.PasswordResetDoneView): template_name = 'authorization/password_reset_done.html' # TODO. I have no idea how to get email address that was entered in 'password_reset' step # email = 'example@gmail.com' mbox, mserver = email.split('@') extra_context = {'mserver': mserver} -
What is the best way to schedule a task, scheduler or bots?
I'm making a website, and I need everyday some specific tasks will run automatically at a specific time.What's the best way to do that? -
How do I annotate a django queryset with StringAgg or ArrayAgg concatenating one column from mulitple children rows?
Documents is the parent table. Paragraphs is the child table. Users filter Documents based on various search criteria. Then I wish to annotate Documents with certain Paragraphs filtered by a text query. The same text query is used to filter Documents and rank them (SearchRank). This ranking makes it necessary to start from Documents and annotate them with Paragraphs, instead of starting from Paragraphs and grouping them by Document. The postgresql way of concatenating one text field from multiple rows in Paragraphs would be the following: SELECT array_to_string( ARRAY( SELECT paragraph.text FROM paragraph WHERE document id = '...' ORDER BY paragraph.number), ''); I am trying to translate this into django coding. I have tried numerous django approaches, to no avail. I can annotate 1 Paragraph. Query_sum is a Q() object built from user input. results = Documents.filter(Query_sum) sub_paragraphs = Paragraphs.filter(Query_sum).filter(document=OuterRef('id')) results = results.annotate(paragraphs=Subquery(sub_paragraphs.values('text')[:1], output_field=TextField())) Problems start when I get rid of slicing [:1]. results = results.annotate(paragraphs=Subquery(sub_paragraphs.values('text'), output_field=TextField())) I then get the following error: "more than one row returned by a subquery used as an expression". To fix that, I tried to use ArrayAgg and StringAgg. I made quite a mess ;-) The Documents queryset (result) should be annotated either with … -
how to override returned serializer object that is returned with the response django rest framework serializer
I have a django rest framework project. I want to override the returned json object structure when a get request is made to display a specific way not similar to the database structure. My current return object is displayed like so: { "id": 9, "namespace": "steve", "path": "something/another", "value": "this is a value", "person": 1 }, { "id": 11, "namespace": "namespace1", "path": "path2", "value": "anyoher value", "person": 2 }, { "id": 12, "namespace": "namespace1", "path": "path3", "value": "this dsiaalks", "person": 2 }, { "id": 13, "namespace": "namespace2", "path": "path4", "value": "asdfasdfasdf", "person": 2 }, I want to switch the "person":2 to display "user":{ "userId":testUser } testUser is the username of the user with id 2 * THis is my current serailzer: from rest_framework import serializers from .models import Preference from django.contrib.auth.models import User class PreferenceSerializer(serializers.ModelSerializer): person = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(),) class Meta: model = Preference fields = ('id', 'namespace', 'path', 'value', 'person') and this is the current model: from django.db import models from django.contrib.auth.models import User from owf_framework.people.models import Person class Preference(models.Model): id = models.BigAutoField(primary_key=True, null=False) version = models.BigIntegerField(default=1, null=False) path = models.CharField(max_length=200, null=False) namespace = models.CharField(max_length=200, null=False) value = models.TextField(null=False) user_id = models.BigIntegerField(null=False, default=1) person = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return … -
Django rest framework - no such table
I'm trying to create an API endpoint on my Django project to retrieve data from my frontend. I'm using two DBs on my django project, the first one is a SQLite DB, the second one is a MongoDB database, the data i need to retrieve is on MongoDB. Here is my model: class tst(models.Model): _id = models.CharField(max_length=100) ticker = models.FloatField() def save(self): # ALL the signature super(Trade, self).save(using='dbtwo') Here is my view: class tstList(generics.ListCreateAPIView): queryset = tst.objects.all() serializer_class = tstSerializer And the url: path('tst/', views.tstList.as_view()), Everything is alright here but when i try to open the API from my browser, i keep getting the following error: OperationalError at /tst/ no such table: main_tst I think this happens because it tries to look for the table tst on the first SQLite database, instead of looking for it on the MongoDB one. Is there any way to solve this? I thought that adding using='dbtwo' would do it, but it's not the right solution. Every advice is appreciated! -
Django - Render HTTP before database connection
I have a serverless database cluster that spins down when it's out of use. Cold starts take a minute or so, during which django just waits and waits to send the http request object back. Before I code something complicated, I'm looking for recommendations for an existing middleware/signal integration that would allow me to render an interim view while django attempts to get the database connection (for instance, if the database query takes longer than a second to complete, render to this view instead.) -
Django multi-form validation from different models
I have been struggling to normalize a few tables/models I have in Django that are to be used in one large form. Let's say I have 2 forms based off of 2 models, 1 of which is dependant of the other. Is there a way to add form validations in 1 model when a specific selection is made in a different model? I can provide code if it'll help, but want to see if this is even possible. So basically, in 1 form I need to reference fields which are in a different model (a different modelForm that's instantiated on the same page) Form2 based off table/model2 : def clean(self): cleaned_data = super().clean() if 'model1_field' in cleaned_data and not cleaned_data['model2_field']: self.add_error('model2_field', forms.ValidationError('This field is required.')) else: print('No validations are needed') -
Accessing the request object from within a class based view? Needed to determine if the request is coming from a mobile device
I have the following CBV: class Index(TemplateView): template_name = 'index_app/index.html' As well as a function that could take the a request object and return whether its coming from a mobile device or not: def mobileBrowser(request): mobile_browser = False ua = request.META['HTTP_USER_AGENT'].lower()[0:4] if (ua in mobile_uas): mobile_browser = True else: for hint in mobile_ua_hints: if request.META['HTTP_USER_AGENT'].find(hint) > 0: mobile_browser = True return mobile_browser I want to be able to use this to do something like the following in my CBV: class Index(TemplateView): if mobileBrowser(request): template_name = 'index_app/mobile/index.html' else: template_name = 'index_app/index.html' This isn't possible, as a CBV doesn't seem to have access to the request object. Is there any way that this object can be accessed in this situation? I know it would be possible to create a standard view instead, but later on I would like to continue using CBVs like CreateView and whatnot, which will just land me in the same situation again.