Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add Token to a model that extends the User Model in Django Rest Framework?
I have the following to create a user and add a Token to it: User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password', 'first_name', 'last_name', 'email') extra_kwargs = {'passwords': {'write_only': True, 'required': True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) token = Token.objects.create(user=user) return user I would like to be able to do the same thing for a Player: class PlayerSerializer(serializers.ModelSerializer): class Meta: model = Player fields = '__all__' def create(self, validated_data): # what to do here? How to create a new token for 'Player'? The Player model extends the 'MyUser' model: class MyUser(AbstractUser): pass class Player(MyUser): national_id = models.CharField(max_length=10) def save(self, *args, **kwargs): self.username = self.email return super().save(*args, **kwargs) -
How to fetch and count duplicate objects in (merged) querysets? [Django]
I am trying to find all duplicates between the current and previous project(s) and count them in order to show the number of the duplicates (or in my case the "returning" visitors from a previous project). The following code works as intended partially, but the issue here is that it will return the correct number of "returning visitors" only if there are two projects available, and it will mess up the things if there is a next project added. For example: The first project have 5 unique visitors. In the second project there are 5 visitors as well, but 3 of them are returning from the first project. At this point the app will show 3 returning visitors which is correct. But if I add the third project, that will have 5 new visitors but only 1 of them is returning from both previous projects and the remaining 4 are new visitors - it will return result as if there are 3 returning visitors again. In this example, my goal would be to show that for the third project, there is only 1 returning visitor from the previous projects (any of the previous or both). So far I have this … -
How can I make a reservation with Django rest framework?
I'm coding a rest API with Django rest. I have a Room model I want to users can reserve the rooms. the rooms have price, reserve days. I created two another models named "order" and "order-item" they are linked together with Stacked Inline in admin.py . with these two models I want to create a order and with a total price function I want to calculate the total price of the reservation ("room price" * "reserve days") . I used Model Serializer for serializing my models. I can't write views.py please help me write my view. from django.contrib.auth.models import User from django.db import models from eghamat.models import Room class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created',) def __str__(self): return f'{self.user} - {str(self.id)}' def get_total_price(self): total = sum(item.get_cost() for item in self.items.all()) return total class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='order_items') price = models.IntegerField() quantity = models.PositiveSmallIntegerField(default=1) def __str__(self): return str(self.id) def get_cost(self): return self.price * self.quantity -
Mysql is not connecting Docker
I am trying to connect mysql docker container on live server but Its not working My docker-compose file is db: image: mysql:5.7 restart: always env_file: - ./todolist/todolist/.env volumes: - ./mysql-data:/var/lib/mysql ports: - "3302:3306" and my env file is like MYSQL_PORT=3306 MYSQL_DATABASE=mydb MYSQL_USER=root MYSQL_PASSWORD=root MYSQL_ROOT_PASSWORD=root and my Django settings.py is DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': mydb, 'USER': root, 'PASSWORD': root, 'HOST': db, 'PORT': 3306, } } and error log on gitlab CI is Creating test database for alias 'default'... Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "/usr/local/lib/python3.6/site-packages/MySQLdb/__init__.py", line 130, in Connect return Connection(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)") -
how to update a table field after BooleanField is clicked
lets think you have a table like this MODELS.PY class test(models.Model): name = models.CharField(max_length=20) pluspoints = models.BooleanField(default=False) minuspoints = models.BooleanField(default=False) total_points = models.IntegerField() def __str__(self): return str(self.name) points.html <form id="points_form"> {% csrf_token %} <div class="row"> <div class="col-3"> {{ form.name|as_crispy_field }} </div> <div class="col-3"> {{ form.pluspoints|as_crispy_field }} </div> <div class="col-3"> {{ form.minuspoints|as_crispy_field }} </div> </div> <br> <input class="btn btn-outline-primary" type="submit" name="submit" value="give the points" /> </form> now, I want to update the "total_points" -1 when I click on minuspoints and +1 when I click on pluspoints. Is this possible? or what could I do else. -
How to send a CSRF token from Django to Vue
My web app is divided into two directories, front-end and back-end, and they hosted on a different domains, because the domains are different, I can't get a CSRF token from cookie file, for Vue to send a post request. How can I get this token in that case? -
DRF: Source reference without re-define field
I'd like to change field name in DRF ModelSerializer without the need to re-define the field I am pointing to. According a post on SO (ref), one can re-name a field name within the serializer by using source, such as: location = serializers.CharField(source='alternate_name') However, this method takes away the benefits of using a ModelSerializer as you essentially need to re-write the field completely, which is a pain when you have many fields. in my case, I have a model field such as: product_uid = models.UUIDField(primary_key=False, unique=True, default=uuid.uuid4, editable=False) In the API, I'd like the field to be called 'uid'. If I would do the following: uid = serializers.UUIDField(source=product_uid) would result in editable=True Is there a way to reference to a ModelField and keep its definition intact according the Model (as you normally do when using serializers.ModelSerializer) but only change the name, e.g. something like: uid = serializers.ModelField(source=product_uid) ? -
why signal triggered in wrong time?
I'm creating a signal which creates a profile for the user considering the group they are in. For example if they user is in TEACHER group the teacher_profile would be created for it. The problem is that the signal triggered before the group of user has been set and gives me the error 'NoneType' object has no attribute 'name'. #views.py def register_page(request): if request.POST: password = request.POST['password'] repassword = request.POST['repassword'] username = request.POST['username'] GROUP = request.POST['group'] if password == repassword: #creating user user = User.objects.create(is_superuser=False, username=username) user.groups.set([Group.objects.get(name=GROUP), ]) user.set_password(password) user.save() #authenticating user user = authenticate(username=username, password=password) if user: login(request, user) return redirect('/esadra/user/dashboard/') else: messages.error(request, 'پسورد ها مطابقت ندارند') messages.error(request, 'فرم را درست پر کنید') #models.py @receiver(post_save, sender=User) def user_profile_creator(sender, instance, created, *args, **kwargs): if created: if instance.groups.first().name == 'TEACHER': profile = teacher.objects.create(user=instance) elif instance.groups.objects.first().name == 'Student': profile = student.objects.create(user=instance) I have tried `m2m_changed` that made other problems for `set_password` , it made the user instance `None type` because it should be saved to trigger the `m2m_changed` signal. -
How to access websocket send_message from django view
I have successfully established a dummy websocket where the client and the server have a handshake. when the userA logs-in the JS whenLoadingPage takes care of the connection and receives a message from django that the connection was established. My question: say I have a background task and I wish to notify the user that the task is completed at the end. How can send a notification from the view? on the JS: function whenLoadingPage() { console.log("WS TEST...") var loc = window.location; var wsStart = 'ws://'; var endpoint = wsStart + loc.host +'/websocket/dummy_consumer/'; socket = new WebSocket(endpoint); socket.onopen = function() { message = {"command":"hello world"} var messageJSON = JSON.stringify(message); socket.send(messageJSON); } socket.onmessage = function(e) { try{ console.log("got it..."); console.log(event.data); }catch(err) { console.log(event) } } } the consumer on django: class DummyConsumer(AsyncConsumer): async def websocket_connect(self, event): print ("dummy consumer initializing...") await self.send({ "type": "websocket.accept", }) async def websocket_receive(self, event): message = event['text'] print ("I received a message from JS:---->"+message) print ("working on my long request...") await asyncio.sleep(0.1) await self.send({ 'type': 'websocket.send', 'text': 'heres your data', }) async def send_message(self, event): await self.send({ "type": "websocket.send", 'text': 'this comes from the view!' }) async def websocket_disconnect(self, event): print("websocket_disconnect ", event) //result on django: … -
How to login using http request for Django
I am writing a backend for an app. Trying to send something like http://127.0.0.1:8000/httplogin/username/password/ to authenticate said user and login as that user with following view function: def httplogin(request, username, pw): username=str(username) pw=str(pw) #both string for username and pw are captured successfully print(request.user.username) user=authenticate(username=username, password=pw) print(user) login(request,user) return HttpResponse("Welcome back "+request.user.username) However, all I keep getting back is request still logged in as Anonymous user or the user previously logged. How do I switch away from Anonymous user? -
Avoid repeated entries from same user
I'm trying to build an auction site. I've set up my placebid view and I'm quite happy with how it functions but the problem is the same user is able to bid on the same listing multiple times. This is okay but instead of it being stored in the database as several separate bids all by the same user, I want the initial bid to be updated or initial bid removed and new bid created. I did try UniqueConstraint and added to my Bid model (fields: bidder and bid_input) but it made no difference plus when I deleted it from my Bid model and makemigrations there were no changes detected so it seems the database was dismissing it anyway. I tried to do a .filter().exists() check before saving the form in my placebid view and now the form lets me place an initial bid but when I do a second bid it returns a Page Not Found error: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/listing/3/bid Raised by: auctions.views.placebid No Bid matches the given query. This is my functional views.py with no form validation checking: def placebid(request, id): listing_bid = get_object_or_404(Listing, id=id) highest_bid = Bid.objects.filter(bid_item_id=id).aggregate(Max('bid_input'))['bid_input__max'] or Decimal('0') currentHighest … -
How can i create global django prefix?
How I can create URLs like this: main url: ecommerce.com with prefix: ny.ecommerce.com moscow.ecommer.com And then I want to use this .ecommerce.com in functions, how I can retrieve it? -
how to make summation of two or more similar objects and prevent creating the new one if its exists ? django
i try to make a system for a storage , sometimes it happen two similar objects are entry in two different time , i have to summation the quantity of both and looks like one object instead of two different object for example i've entry this data one week ago name=mouse , qnt=20 , price=20 and today i add a new collection of mouse (the same mouse as before) name=mouse , qnt=10 , price=15 i have to whenever i face similar problem it automatically summation quantities =(30) and price = ((20+15)/2) instead of creating a new object to the second mouse object is it possible ? or is there anything else for similar issues ?! this is my model this is the Products model class Products(models.Model): name = models.CharField(max_length=20,unique=True) qnt = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=3,null=True,blank=True) def __str__(self): return self.name this is the Collections model class Collections(models.Model): name = models.ForeignKey(Products, on_delete=models.CASCADE) qnt = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=3,null=True,blank=True) i dont need to create new object to the same product as exist in collection , i have to just summation the quantities ?! is it possible ?thanks -
How can I determine if a string in Django model list field contains a substring?
How do I write a filter like this: MyObject.objects.filter(some_string__icontains="match") for each string in a list field like this: MyObject.objects.filter(some_list__icontains="match") # Not working So if some_list in a MyObject looks like this: some_list = ["item1", "item2", "item3match"] the query above should find it -
Wagtail - show latest 3 posts but filter the 3 posts when in the latest post selected
bit hard to explain this one but I will give it my best. I am trying to develop a wagtail website and all is looking fine, but now I have come across a problem. In my side panel to the right I have the latest 3 posts published. This always shows the latest 3 posts which is great for further reading but when I select one of those posts in the side panel, the post that I have selected is still visible in the side panel. So basically I am looking for some kind of restructuring to my models to say if post selected, in side panel show the next latest post applicable instead. a visual representation is thus: So my code is as follows: template: <div class="col-2__sm"> <div class="card"> {% for child in page.get_recent_blogs %} <div class="col-1 card__block"> <div class="card__content news-blocks"> <a class="blog__recent-posts" href="{{ child.url }}"> <div class="image"> {% image child.image fill-850x450-c100 %} </div> <h3>{{ child.title }}</h3> <p>{{ child.introduction|truncatewords:15 }}</p> <span>Read More</span> </a> </div> </div> {% endfor %} </div> </div> In my model I have this: def get_recent_blogs(self): max_count = 3 return BlogPage.objects.all().order_by( '-first_published_at')[:max_count] # add this to custom context def get_context(self, request): context = super(BlogPage, self).get_context(request) context['blogs'] = … -
Django - OR filter on two fields, one of which is in related table
I have two models: Post and User (the standard Django User model - thus not shown below) class Post(models.Model): # post_file = CloudinaryField(resource_type='video',blank=True) post_file = models.CharField(max_length=500,blank=False,default="") user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.CharField(max_length=150,blank=False,default="") approved = models.BooleanField(default=False) active = models.BooleanField(default=False) I want to filter Posts where either the post description or the User.user_name contains a search string. e.g. search_crit ='erch' Tried many approaches but the solution keeps evading me. from django.db.models import Q active_post_views = Post.objects.filter(active=True, approved=True).select_related('user') matched_active_post_views = active_post_views.filter( Q(description__contains=search_crit) | Q(username__contains=search_crit) ) -
How to use Docker Volumes?
I am completely new to Docker, right now I am using an open-source tool, which is a Docker application, I need to make some changes to the existing application for my requirement and it should reflect the changes, I did a lot of searching, then I found that we can do this with the help of Docker Volumes, but I am unable to follow any of the articles on the web as well as documentation? Any suggestions will be appreciated. docker-compose.yml: version: "3.3" services: cvat_db: container_name: cvat_db image: postgres:10-alpine networks: default: aliases: - db restart: always environment: POSTGRES_USER: root POSTGRES_DB: cvat POSTGRES_HOST_AUTH_METHOD: trust volumes: - cvat_db:/var/lib/postgresql/data cvat_redis: container_name: cvat_redis image: redis:4.0-alpine networks: default: aliases: - redis restart: always cvat: container_name: cvat image: cvat/server restart: always depends_on: - cvat_redis - cvat_db build: context: . args: http_proxy: https_proxy: no_proxy: nuclio,${no_proxy} socks_proxy: USER: "django" DJANGO_CONFIGURATION: "production" TZ: "Etc/UTC" CLAM_AV: "no" environment: DJANGO_MODWSGI_EXTRA_ARGS: "" ALLOWED_HOSTS: '*' CVAT_REDIS_HOST: "cvat_redis" CVAT_POSTGRES_HOST: "cvat_db" volumes: - cvat_data:/home/django/data - cvat_keys:/home/django/keys - cvat_logs:/home/django/logs - cvat_models:/home/django/models cvat_ui: container_name: cvat_ui image: cvat/ui restart: always build: context: . args: http_proxy: https_proxy: no_proxy: socks_proxy: dockerfile: Dockerfile.ui networks: default: aliases: - ui depends_on: - cvat cvat_proxy: container_name: cvat_proxy image: nginx:stable-alpine restart: always depends_on: - cvat … -
django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint
I want to create a process whereby when a user registers by default he/she is just an ordinary user, then if the user wants additional privileges thereby becoming a "vendor", they have to register with another form (this form should update their already created profile). I tried what i could to this point but i keep getting "null value in column "user_id" violates not-null constraint" when i register with the second form. the UserCreationForm works well, here's the Vendor form: from django import forms from .models import Profile from blog.models import Category from django.db import transaction class VendorRegisterForm(forms.ModelForm): class Meta: model = Profile fields = ['bvn', 'company', 'description', 'address'] @transaction.atomic def save(self): profile = super().save(commit=False) profile.is_vendor = True profile.save() profile = Profile.objects.create(user=user) # student.interests.add(*self.cleaned_data.get('interests')) return profile Model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=245, null=True) image = models.ImageField(default='default.png', upload_to='profile_pics') interests = models.ManyToManyField(Category, related_name='interests_user') is_vendor = models.BooleanField(default=False) # vendor bvn = models.CharField(max_length=10, null=True, blank=True) description = models.TextField(null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) company = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return f'{self.user.username} Profile' @property def followers(self): return Follow.objects.filter(follow_user=self.user).count() @property def following(self): return Follow.objects.filter(user=self.user).count() def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width … -
Django best practice for scripts organizing
I had the project on Django 3.1 with the following layout: . ├── app │ ├── app │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── core │ │ ├── admin.py │ │ ├── apps.py │ │ ├── fixtures │ │ │ ├── Client.json │ │ │ └── DataFeed.json │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_auto_20201009_0950.py │ │ │ └── __init__.py │ │ ├── models.py │ │ └── tests │ │ └── __init__.py │ └── manage.py I want to add 2 scripts to this project: download_xml.py - to check and download .xml files from external sources by schedule (every ~30 min) update_db_info.py - to be invoked by download_xml.py and transfer data from downloaded xml to the database What is the best django practice for organizing a placement for this kind of scripts? My ideas: just create scripts folder inside of an app/core and put scripts there. Invoke them using cron run python manage.py startapp db_update so the new app in django will be created. I will remove migrations, views, models etc from it and put scripts … -
Photos for each post in django
I have created a blog website and I want to display images for every post like YouTube thumbnails. I created an image field in my Post Class but it is not saving my image in the media folder when I create a post. Post class in models.py: class Post(models.Model): name = models.CharField(default='Concert', max_length=100) invite = models.ImageField(default='invite.jpg', upload_to='invite_pics') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) This is my CreatePost class in views.py: class PostCreateView(LoginRequiredMixin, CreateView): model = Post template_name = 'home_page/post_form.html' fields = ['name', 'invite'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) I have set the MEDIA_ROOT and MEDIA_URL in settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' So as I have said earlier, the image is not getting saved to media/invite_pics what should I do? -
Wagtail: Filter Page model by a field on the child
I have two models, ParentPage and ChildPage. I want to find the set of ParentPages where a field is_completed is True on the ChildPage. Normally in Django, I could do something like ParentPage.objects.filter(child_page__is_completed=True) However, I don't think there is a join here for the Wagtail/Treebeard hierarchy. I also thought you might be able to filter ChildPages by multiple ParentPages, e.g. ChildPage.objects.children_of([parent_ids]), but I can't see a way to do that either. Is there a simpler way? -
What are the differences between using serializers and for loop to return a json response?
I am trying to create an API to return some JSON responses with Django. The app is just doing some CRUD operations and integration with Shopify API. From my understanding, I know that I can use Django Rest Framework (DRF), plain Django serializer, or return JSON response on my own. From this thread, I know that DRF can give me a better JSON format than Django serializer. However, is it simpler to just loop the Model and return the JSON Response on my own? For example, for product in products: if 'node' in product: returnProduct = {} node = product['node'] returnProduct['id'] = node['id'][22:] returnProduct['updated_at'] = node['updatedAt'].split('T', 1)[0] returnProduct['title'] = node['title'] returnProduct['short_title'] = node['title'][0:48] + "..." if len(node['title']) > 48 else node['title'] returnProducts.append(returnProduct) data = { "products" : returnProducts} return JsonResponse(data) Is it because it's faster to use serializers than looping on my own? Or am I mixing up different scenarios? -
DJANGO - AudioField - problem with make migration - [ERROR (auth.E005)]
I tried make AudioField with django-audiofield My project settings: INSTALLED_APPS = [ ... 'audiofield', ] MIDDLEWARE = [ ... 'audiofield.middleware.threadlocals.ThreadLocals', ] STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') AUTH_USER_MODEL = 'user.Profile' in my models.py I have: class Beat(models.Model): name = models.CharField(max_length=120) audio_file = AudioField(upload_to='/music', blank=True, ext_whitelist=(".mp3", ".wav", ".ogg"), help_text=("Allowed type - .mp3, .wav, .ogg")) def audio_file_player(self): """audio player tag for admin""" if self.audio_file: file_url = settings.MEDIA_URL + str(self.audio_file) player_string = '<ul class="playlist"><li style="width:250px;">\ <a href="%s">%s</a></li></ul>' % (file_url, os.path.basename(self.audio_file.name)) return player_string audio_file_player.allow_tags = True audio_file_player.short_description = _('Audio file player') I cant make migrations. There is some error: ERRORS: audiofield.AudioFile: (auth.E005) The permission codenamed 'view_audiofile' clashes with a builtin permission for model 'audiofield.AudioFile'. -
ERROR: Can not perform a '--user' install. User site-packages are not visible in this virtualenv
Actually, I wanted to create my first django project. After I did some coding in the cmd then I opened the code using visual studio code. I selected the python interpreter on the status bar, then I changed it to the python interpreter installed in my digital environment. After that, I got message that linter pylint is not installed. After I installed that, these errors occurred. enter image description here -
Electron + React as frontend and Django Rest as backend, would it work?
I have built an API using Django Rest Framework which acts as the backend. As of now, I'm using React JS as frontend, just like any other web application. Now I want to get into building a native desktop app using Electron Js. Is there a way to combine Electron and React as one whole desktop app, which throws request to Django API hosted online? A guideline would be much appreciated. Django also throws a CORS error, which when called from a non-listed url. Usually, when calling from React js as a normal application, we'll list out the port number/base URL as whitelist. How exactly things work when calling it from a desktop app?