Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Simple way to integrate websockets to Django Rest Framework application?
My game app uses Vue frontend and Django backend with DRF. Several clients connect to same game session. Sometimes some user does something which has to be reflected also for other users. For that purpose server has to have means to request client to refresh data. Django application is deployed on Elastic beanstalk. Typical game session has 10 players, update request is sent once in 15 seconds to the players and I don't believe we will for the foreseeable future have more than 50 simultaneous games, so the performance requirement is low. I'm looking for a simple solution to push the update request message to the clients. My current solution uses Redis server running on ec2. When on Django views something is changed, Django publishes update request to Redis: r = redis.Redis(host=settings.REDIS_IP, port=6379, db=0) r.publish(game_identifier, type) "Type" contains information which kind of data should be updated. In addition I've implemented a simple Node application. All clients connect to this app using Websocket. The app also subscribers to Redis, and whenever there is a notification it's emitted to subscribers using their game's identifier as channel. After this the clients refresh their state with REST. Node application is also run on Elastic … -
Adding indexes to MYSQL in Django after database has been created
I added 'db_index=True' to the columns that I want to become indexes in models.py. Then I run this command: python manage.py makemigrations --name add_index_fake Then I try to migrate the changes and I get this - it recognizes the change, but does not create an index: python manage.py sqlmigrate my_app migration_name BEGIN; -- -- Alter field 'columnname' on table -- COMMIT; But I'm not getting this: CREATE INDEX xxxxxx ON "xxxx" ("sold_at"); COMMIT; How can I get Django to create index after database is already built? -
Logic for phased release for a python desktop app
How can I do a phased release for a Python Desktop app? We use PyUpdater to pakckage our application and a button on the python app, when clicked checks for updates. I am considering writing an api in Django that this python app can call to determine if the user is a candidate for the phased release. Can I get some pointers on it? -
how to get pk value of another model in current model's get absolute url django
I am learning django. I am very new to programming. I have one model as below: class Group(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) group_description = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def get_absolute_url(self): self.save() return reverse('group-detail', kwargs={'pk': self.pk}) now I am creating another model which needs the pk value of the above Group model: class GroupPost(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('group-post-detail', kwargs={'pk': Group.pk, 'pk2': self.pk}) when I give just Group.pk it is erroring out giving the below information. Reverse for 'group-post-detail' with keyword arguments '{'pk': , 'pk2': 73}' not found. 1 pattern(s) tried: ['groups/(?P[0-9]+)/post/(?P[0-9]+)/$'] How can I get rid of the error message. what is the correct way to proceed? Any help would be appreciated. Thank you -
how to update a row in django using a form?
I'm trying to make a website to track my employees' attendance using django, there will be a check/in and a check/out button so when the check/in button is clicked the data will go to the database there is no problem with that the problem is in the check/out button, when the check/out button is clicked it should update the row and add the date/time of the check/out. -
Get items from request.FILES
I tried to get items by request.FILES: from input <input type='file' name='images' multiple> I recieve to django views the data: <MultiValueDict: {u'images': [<InMemoryUploadedFile: Men_Mother_Boys_Little_girls_Smile_Glance_558746_1280x853.jpg (image/jpeg)>, <InMemoryUploadedFile: tumblr_p4fq65rkPh1uc0ho8o1_1280.jpg (image/jpeg)>, <InMemoryUploadedFile: tumblr_nxq18wYT4l1uc0ho8o1_500.jpg (image/jpeg)>, <InMemoryUploadedFile: ddc4790b00ee3c8d51c106afa76a4dc7.jpg (image/jpeg)>, <InMemoryUploadedFile: 9961f0d0ea1b54cdd9d4a2c58a66c6be.jpg (image/jpeg)>]}> I try get the list of files: images = self.request.FILES.get('images', None) But in images always I receive just single InMemoryUploadedFile, although I expect list of InMemoryUploadedFile. I checked: print(type(self.request.FILES)) #<MultiValueDict: {u'images': [<InMemoryUploadedFile: print(type(images)) #InMemoryUploadedFile I find this rather atypical for behavior a dictionary. Maybe this is a pre-planned behavior intended to receive for single file? Is that how it should be? -
Django runserver error: _frozen_importlib._DeadlockError: deadlock detected by _ModuleLock('django.test.signals') at 139824587568800
After adding 'rest_framework.authtoken' to INSTALLED_APPS (settings.py) and running python manage.py migrate I started to get a strange error when trying to run django server (the strange thing is, that the error appears on every 2nd or 3rd attempt, sometimes the server starts running without the error): Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/home/username/.local/share/virtualenvs/blogapi-nhgDNK6P/lib/python3.7/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/username/anaconda3/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/home/username/anaconda3/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/home/username/.local/share/virtualenvs/blogapi-nhgDNK6P/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/username/.local/share/virtualenvs/blogapi-nhgDNK6P/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/username/.local/share/virtualenvs/blogapi-nhgDNK6P/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/home/username/.local/share/virtualenvs/blogapi-nhgDNK6P/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/home/username/.local/share/virtualenvs/blogapi-nhgDNK6P/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/username/.local/share/virtualenvs/blogapi-nhgDNK6P/lib/python3.7/site-packages/django/contrib/admin/checks.py", line 79, in check_dependencies for engine in engines.all(): File "/home/username/.local/share/virtualenvs/blogapi-nhgDNK6P/lib/python3.7/site-packages/django/template/utils.py", line 90, in all return [self[alias] for alias in self] File "/home/username/.local/share/virtualenvs/blogapi-nhgDNK6P/lib/python3.7/site-packages/django/template/utils.py", line 90, in <listcomp> return [self[alias] for alias in self] File "/home/username/.local/share/virtualenvs/blogapi-nhgDNK6P/lib/python3.7/site-packages/django/template/utils.py", line 81, in __getitem__ engine = engine_cls(params) File "/home/username/.local/share/virtualenvs/blogapi-nhgDNK6P/lib/python3.7/site-packages/django/template/backends/django.py", line 25, in __init__ options['libraries'] = self.get_templatetag_libraries(libraries) File "/home/username/.local/share/virtualenvs/blogapi-nhgDNK6P/lib/python3.7/site-packages/django/template/backends/django.py", line 43, in get_templatetag_libraries … -
Duplicate key error when saving a new user
I'm trying to save a User and a Profile in django which are linked together using a oneToOneField but I'm getting an error saying duplicate key value violates unique constraint "auth_user_username_key eventhough I dont have any duplicates. I also get this error: duplicate key value violates unique constraint "api_profile_user_id_key" DETAIL: Key (user_id)=(9) already exists. Here is my code: model.py from django.db import models from django.contrib.auth.models import User from django.db.models import CharField, OneToOneField from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = OneToOneField(User, on_delete=models.CASCADE) phone_number = CharField(max_length=20) account_type = CharField(max_length=10, default='basic') facebook_id = CharField(max_length=20, blank=True) google_id = CharField(max_length=20, blank=True) notification_id = CharField(max_length=40, blank=True) # TODO add account info and watchlist def __str__(self): return self.user.email @receiver(post_save, sender=User) def user_save(sender, instance, **kwargs): Profile.objects.create(user=instance) view.py: @api_view(['POST']) def sign_up(request): data = request.data user = User.objects.create_user(username=data['username'], password=data['password'], first_name=data['first_name'], last_name=data['last_name'], email=data['email'] ) user.profile.phone_number = data['phone_number'] user.save() return Response('hey') I think the problem is in the post_save receiver however I'm not sure. -
How to use concat and chr function in a django queryset?
I'm trying something like this: my_field=Concat( (chr(65) + F("foo")), F("bar") + Value(1), output_field=CharField(), ) But I got this error: invalid input syntax for integer: "A" foo and bar return a integer and I expect "A1, A2" like a result. -
update the DTL cycle without rebooting
Suppose my template has a lot of content that is generated using a DTL loop, which also has a lot of content. How can I, after an ajax request, update part of the content without reloading the page and display the new content using the DTL cycle? (I do not consider it necessary to insert the code, since the question requires a general answer) -
Django admin group permissions for CBV's
I am working on an app and right now I am dealing with a specific admin group that I created called post admin. In my django admin I have the permissions for the group set to Can Change Post, Can Delete post, Can View Post I want to give my post admin group users better access to be able to do this. Not just in the admin page. I want them to be able to go to my DeleteView, UpdateView and be able to edit/delete any users posts. So basically I need to be able to give access to the view to the user who originally created the post and my post admin group. Any tips/advice how to incorporate this? -
Filtering a Django model using the related names of 2 M2M fields
I have the following structure in my models: class Sauce(models.Model): ... class Topping(models.Model): ... class Pizza(models.Model): sauces = models.ManyToManyField(Sauce, related_name='pizzas') toppings = models.ManyToManyField(Topping, related_name='pizzas') Now, lets say I want to query all the pizzas given a list of toppings and sauces. For example: sauces_ids = [2, 5, 7, 8] toppings_ids = [1, 4, 5, 21] What is the most efficient way to query this using Django's ORM? Thanks for any help. -
I need to allow users to upload photos but my form is in forms.py not HTML
Our users are uploading photos through form.py ProfileForm, which is currently only allowing the admin to upload photos to the site. We added enctype="multipart/form-data" to our html that is rendering the form, but it still wont allow the user to upload their photos. class ProfileForm (forms.ModelForm): class Meta: model = Profile fields = ('nickname', 'gender', 'age', 'height', 'location', 'job_title', 'education', 'hometown', 'drinker', 'smoker', 'photo_one', 'photo_two', 'photo_three', 'prompt_one', 'prompt_two', 'prompt_three', 'age_preference_max', 'age_preference_min', 'gender_preference') {% extends 'base.html' %} {% block content %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> {% endblock %} -
Django adding custom admin.py to project causes error of not detecting one of applications in INSTALLED_APPS
I am doing a project which could be found here. If you check the link you find out that I have changed the default structure a little bit and its something like this: config/ env/ .env files requirements/ __init__.py ... settings/ __init__.py base.py local.py __init__.py urls.py views.py wsgi.py projects/ api/ town/ apps.py urls.py views.py ... core/ models/ town.py .... admin.py apps.py views.py serializers/ town_serializer.py ... tests/ test_town.py manage.py The project tests were running with no problem until I decided to develop customized admin located in project/core. This is admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from core import models class UserAdmin(BaseUserAdmin): ordering = ['id'] list_display = ['email', 'name'] admin.site.register(models.User, UserAdmin) very simple as you see. After writing this I run the previous test and I found this error: RuntimeError Model class core.models.town.Town doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Which is really weird because I already have registered it in INSTALLED_APPS. take a look at base.py in config/settings/ directory file which is part of default settings.py file of django: DJANGO_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) THIRD_PARTY_APPS = ( 'rest_framework', 'django_filters', ) LOCAL_APPS = ( 'project.core.apps.CoreConfig', 'project.api.city.apps.CityConfig', 'project.api.town.apps.TownConfig', … -
Django urls.py deprecated, urlpatterns to change
I try to compile an old code in Django 1.4 Many things are deprecated. I manage to change some of them but I don't knwo how to go futher on the urls.py here is the old code from django.conf.urls.defaults import * from django.conf import settings dynurls = patterns('minesweepr.views', (r'^api/minesweeper_solve/$', 'api_solve'), ) staticurls = patterns('minesweepr.views', (r'^player/$', 'template_static'), (r'^query/$', 'template_static'), ) urlpatterns = patterns('', ('^%s' % settings.BASE_URL, include(dynurls)), ('^%s' % settings.BASE_STATIC_URL, include(staticurls)), ) I know django.conf.urls.defaults is deprecated and I tried to change the code like this from django.conf.urls import url, include from django.conf import settings dynurls = ['minesweepr.views', (r'^api/minesweeper_solve/$', 'api_solve'), ] staticurls = ['minesweepr.views', (r'^player/$', 'template_static'), (r'^query/$', 'template_static'), ] urlpatterns = ['', ('^%s' % settings.BASE_URL, include(dynurls)), ('^%s' % settings.BASE_STATIC_URL, include(staticurls)), ] But it is not sufficient It is said my url patterns are invalid. Anybody has an idea ? Thank you -
GitLab Job failed Django + Postgres project
I'm using Gitlab Job to build and test my Django project. I can't run my tests because my web container (the django one) is always restarting. I'm using a script .wait-for-postgres.sh to run my web container after the postgres one but it doesn't change anything. For info I'm using a scpefic Runner running inside a Gitlab container. Here is my config.toml file : concurrent = 1 check_interval = 0 [session_server] session_timeout = 1800 [[runners]] name = "Core API Runner" url = "https://gitlab.com/" token = "<my-token>" executor = "docker" [runners.custom_build_dir] [runners.docker] tls_verify = false image = "docker:stable" privileged = false disable_entrypoint_overwrite = false oom_kill_disable = false disable_cache = false volumes = ["/var/run/docker.sock:/var/run/docker.sock", "/cache"] shm_size = 0 [runners.cache] [runners.cache.s3] [runners.cache.gcs] And here is my runner output : -
Blog Post doesn't show images, bold text, or other attributes only the raw code... Django/Ckeditor
I've followed a tutorial on implementing a ckeditor RichTextUploadingField() to my blog so I can have more functionality and better looking post/blogs. Everything seems to be working but when I go to see the actual post after adding the picture and some words. I get a raw output with all my text... Here is my output on my blog <p><span style="color:#1a1a1a"><span style="background-color:#ffffff">First of all, I have assumed that you have seen countless rubbish articles, and still can&#39;t understand classes and objects, but at least know that there are two things like classes and objects.</span></span></p> <p><span style="color:#1a1a1a"><span style="background-color:#ffffff">Since you don&#39;t have programming experience, you can&#39;t understand Python&#39;s &#39;classes and objects&#39; by analogy from the programming language you&#39;ve learned.&nbsp;Let&#39;s use the example of life to build a house.</span></span></p> <p>&nbsp;</p> <p><span style="color:#1a1a1a"><span style="background-color:#ffffff"><img alt="" src="/media/upload/2019/11/08/01.png" style="height:268px; width:400px" /></span></span></p> Not sure why it doesn't look like the output I get before I post the article while I'm editing and creating it. MODELS.PY from ckeditor_uploader.fields import RichTextUploadingField from django.contrib.auth.models import User from django.db import models from django.urls import reverse from django.utils import timezone class Post(models.Model): title = models.CharField(max_length=100) # content = models.TextField() content = RichTextUploadingField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return … -
How to accses queryset created by view in serializer so I can do some calculations based on it
I have a review model which has a large data so, first I want to filter based on the date range, I actually did that like this, class ProgressView(generics.ListAPIView): """ Return a list of all Feedback reviews for progress. """ serializer_class = ReviewProgressSerializer filterset_class = ProgressFilter pagination_class = UnlimitedPagination def get_queryset(self): return Review.objects.filter(division__pk=self.kwargs['division_pk']) Now I want to do some calculations based on this filtered queryset, but the problem I have is how to access this queryset and do calculations on it, I don't know how to do that in the serializer or should I do it in view. Please note that I need to do both, serialize the review data and return calculations too. I feel like there is a way to do both in one place because in the end, it is only one queryset so there must be a way to do anything I want with it in one place. so my question is how to access the queryset created by view in serializer or should I do that in another place or what. Thank you -
why can't I log in into any account until I reset its password in django admin?
I have a Profile model that has a one to one relationship with the User model from django.contrib.auth.models , when I add a new profile from the admin panel I noticed that the password field is not transformed into dots when typing , it shows the actual password , that's not the issue though , the issue is , when ever I create a new profile which in turns creates a new User , and mark the is staff attribute as true, I can't log in into the admin panel with that created account, unless I reset the password manually with python manage.py changepassword the-user-name after I have reset the password and only then even with the same password, I can log in into the account normally, does anybody know why is that happening ? I made sure it's not a mistake in typing the password and I tried it several times until I made sure that this is what is actually happening -
django deferring all fields in a related model queryset
I have a query where I need the second related model Model1.objects.all().select_related("model2__model3") but I don't need any field from model2, only many different fields from model3, e.g. obj.model2.model3.name and others How can I defer all fields from model2 without explicitly mentioning them one after the other? -
From where should we hit third party apis in django?
I'm a beginner in django. So my current structure is --/project ----/settings.py ----/urls.py ----/wsgi.py --/app1 ----/migrations ----/admin.py ----/apps.py ----/models.py --/app2 ----/migrations ----/serializers.py ----/apps.py ----/urls.py ----/views.py I want to know where and how (to access) should i code some things: I want to connect with a third party storage service by hitting their apis and getting the data i need. I want to store that data in my database in some model I created in models.py let's say 'Setting' I want to generate some more data using Setting data and store it in database for another model let's say 'Item' Finally the Item is what will be sent in the response for the rest api of my app which i have already achieved. Right now I am hitting the third party apis inside my views.py like this: class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer_class = serializers.ItemSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get_queryset(self): return self.queryset.order_by('order_id') def perform_create(self, serializer): """Create a new Item""" # generate some auth string and hit api # http = urllib3.PoolManager() # response_auth = http.request( # 'GET', # SOME_URL, # headers={auth: auth_string}, # ) # print(response_auth.status) # print(response_auth.data) # auth_response = json.loads(response_auth.data.decode('utf8')) # print(auth_response) # serializer.save(user=self.request.user, name=auth_response['name']) Also … -
Hello. I am having a problem to change the pages in my django project that it shows a page not found (404)
I've been building my first Django project, and I was doing the "login page", and it is working, but when then, I've made a condition that if the login is wrong, it comes back to the login page and shows an error message, and if it is right, it should go to a page where is written "logadissimo", but when I try this last one, I get the problem below: Page not found (404) Request Method: GET Request URL: http://localhost:8000/ Using the URLconf defined in sitetcc.urls, Django tried these URL patterns, in this order: admin/ login/ login/submit login/logado The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. this is my url.py from the project: Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls.conf import include from django.urls import path from core import views urlpatterns = [ … -
got issue OSError at /password-reset/ [Errno 101] Network is unreachable in django when send emails
try to send emails from django on localhost. previously everything works well, but now see that issue. net conection is ok. cant find info about how to solve it in the django. pleese help. here is a part of my settings.py file: # sending email for password reset EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '***@gmail.com' EMAIL_HOST_PASSWORD = 'google app key' -
trying to get the messages frame work to display message if valid and invalid
For some reason django displays both success message and failure message when I'm trying to display messages on form creation and update. Here I'm copy pasting the code for only the form creation. The view I'm using is: #function based views def post_create(request): form = PostForm(request.POST or None) # if request.method == "POST": # # print(request.POST) # print("title: ", request.POST.get("title")) # print("content: ",request.POST.get("content")) if form.is_valid(): instance=form.save(commit=False) print(form.cleaned_data.get("title")) instance.save() #a success message messages.success(request, "Successfully Created") return HttpResponseRedirect(instance.get_absolute_url()) else: messages.error(request, "Post Not Created") context= { "form":form } return render(request, "post_form.html",context) and the Post model is also very basic: class Post(models.Model): title = models.CharField(max_length=120)#; content = models.TextField()#: updated = models.DateTimeField(auto_now = True, auto_now_add=False)#; save and update everytime change is done timestamp = models.DateTimeField(auto_now = False, auto_now_add = True)#; auto_now_add = save and set one time def __unicode__(self): return self.title #python3 def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"id":self.id}) the form template is: <html> <head><title>new page</title></head> <body> <h1>Form</h1> <form method="POST" action=""> {{ form.as_p }}{% csrf_token %} <input type="submit" value="Create Post"/> </form> </body> </html> and the page where the message gets displayed is: <!DOCTYPE HTML> <html> <head> <title> index.html </title> </head> <body> {% if messages %} <ul class="messages"> {% for message in messages %} … -
Django: django.urls.exceptions.NoReverseMatch: Reverse for 'update' with arguments '('',)' not found
When I'm trying render template after login I get django.urls.exceptions.NoReverseMatch: Reverse for 'update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['users/(?P[0-9]+)/update/$'] My line in urls.py: app_name="users" ... path("users/<int:pk>/update/", view=user_update_view, name="update"), And line in template: <a href="{% url 'users:update' pk=request.user.pk %}">Update user</a> I see that request.user.pk not giving value, but I don't know why.