Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serializer.data gives old values, new ones visible in serializer in DRF
I wrote a custom perform_update(self, serializer) function in a ViewSet but I am having trouble updating the data. In the code below I see the data={} dictionary containing the old values (that are already in the DB) while the second print shows the data as it was posted. Can anyone please explain how I can use the updated data and why the old data shows up with serializer.data? (See the difference between 'source' and 'verwerking' values in the two prints) class RegisterlineViewSet(viewsets.ModelViewSet): queryset = Registerline.objects.all() serializer_class = RegisterlineSerializer permission_classes = [permissions.IsAuthenticated] ... def perform_update(self, serializer): print(serializer.data) print(serializer) Result: {'id': 4, 'external_reference': OrderedDict([('source', '7777777'), ('sourcekey', '77777'), ('last_updated', None)]), 'verwerking': '', 'applicatienaam': ... RegisterlineSerializer(<Registerline: @ [4]>, context={'request': <rest_framework.request.Request: PATCH '/api/registerline/4/'>, 'format': None, 'view': <core.views.RegisterlineViewSet object>}, data={'id': 4, 'external_reference': {'source': '7777gfhngtn777', 'sourcekey': '77777', 'last_updated': None}, 'verwerking': 'gnyghnj',... -
How to convert (and maybe optimize) the following raw query to Django Queryset
I have the following query: SELECT OBJ_DESC_ERRORS.description, OBJ_DESC_ERRORS.object, OBJ_DESC_ERRORS.count_errors, OBJ_ERRORS.count_total FROM (SELECT `metrics_event`.`description`, `metrics_event`.`object`, COUNT(`metrics_event`.`id`) AS `count_errors` FROM `metrics_event` INNER JOIN `metrics_session` ON (`metrics_event`.`session_id` = `metrics_session`.`id`) WHERE (`metrics_session`.`training_id` = 4 AND NOT (`metrics_session`.`completed_at` IS NULL) ) GROUP BY `metrics_event`.`description`, `metrics_event`.`object` ORDER BY `count_errors` DESC ) as OBJ_DESC_ERRORS JOIN (SELECT `metrics_event`.`object`, COUNT(`metrics_event`.`id`) AS `count_total` FROM `metrics_event` INNER JOIN `metrics_session` ON (`metrics_event`.`session_id` = `metrics_session`.`id`) WHERE (`metrics_session`.`training_id` = 4 AND NOT (`metrics_session`.`completed_at` IS NULL) ) GROUP BY `metrics_event`.`object` ORDER BY `count_total` DESC ) as OBJ_ERRORS ON OBJ_DESC_ERRORS.object = OBJ_ERRORS.object which produces the following result: As you can see I'm basically running the same query twice. The reason for that is that I need to have that count_errors broken down by each aggregation of object + description, but I also need the count_total to be only aggregated by object. This was the way I could think of. Now I'd like to: How to write this using Django Queryset language ( I get stuck at the join/subquery parts) If there's a way to optimize this query (performance or clarity or both) I hope I'm not cheating with 2 questions in 1. Felt like a duplicate to create an entire copy+paste question description for 2 different … -
Ajax code for the Add to Favorites button in Django
I want to create a button to add to favorites according to the image below View codes like this def product_favorites_user(request, product_id): product = Product.objects.get_by_id(product_id) user_favorites = get_object_or_404(User, id=request.user.id) if request.method == 'POST': if product in user_favorites.favorites.all(): user_favorites.favorites.remove(product) else: user_favorites.favorites.add(product) return redirect(product.get_absolut_url()) html code <ul class="gallery-options"> <li> <form name="favorites-form" method="post" action="{% url 'product-favorites-user' product.id %}"> {% csrf_token %} <button class="add-favorites"><i class="mdi mdi-heart"></i></button> <span class="tooltip-option">افزودن به علاقمندی</span> </form> </li> </ul> The code works properly and the product is added to favorites, but I'm not up to Ajax properly. I wanted to know what the code looks like. -
How do I run multiple sites on the same server using docker and nginx?
I'm trying to run two sites on django on the same server under different ip, an error occurs that the port is busy, I fixed the ports, but the site does not start. Tell me where is the error please? When I go to ip I get an error This site can’t be reached. I have two docker-compose files, and in each of them I run nginx, on the second it gives an error, please tell me how to configure it correctly. I heard there is an option with a common nginx file, but I don't understand how to implement it. Help me please. This is the second docker-compose file and its settings. I would be very grateful for your help .env #Django # Should be one of dev, prod MODE=prod PORT=8008 #postgres DB_NAME=xxx DB_USER=xxx DB_HOST=xxx DB_PASSWORD=xxxx DB_PORT=5432 POSTGRES_PASSWORD=mysecretpassword #WSGI WSGI_PORT=8008 WSGI_WORKERS=4 WSGI_LOG_LEVEL=debug # Celery CELERY_NUM_WORKERS=2 # Email EMAIL_HOST_USER=xxxx EMAIL_HOST_PASSWORD=xxxx docker-compose.yml version: '3' services: backend: build: ./ container_name: site_container restart: always command: ./commands/start_server.sh ports: - "${PORT}:${WSGI_PORT}" volumes: - ./src:/srv/project/src - ./commands:/srv/project/commands - static_content:/var/www/site env_file: - .env depends_on: - postgres postgres: image: postgres:12 volumes: - pg_data:/var/lib/postgresql/data env_file: - .env # environment: # - DJANGO_SETTINGS_MODULE=app.settings.${MODE} nginx: image: nginx:1.19 volumes: - ./nginx:/etc/nginx/conf.d - … -
Having Problems with redirects while using azure auth adfs module
So, I'm trying to build and app that the user logs in using azure, and am usind azure auth adfs for it, and authentication itself is working. The problem is I need my landing page (say localhost:port) to be non dependant in this authentication, or appear for all and just redirect me to login through a button or to the main app thru the login steps. I just can't figure out how to make the redirects that make this possible, can someone give some help, maybe direct me to some resources that shows how to do this while using the azure auth adfs, as I just came across solutions for the normal django authorization process. -
LoginForm django modale
I try to add on a popup(modale)who is on my header a login form based on the LoginForm fonction of django. But it do not work... I don't know what I didn't do correctly... When I use the LoginForm on a page like login.html il work but when I try on the popup page nothing. Here my page popup.html and the my page urls. Thaank you from django.urls import path from django.contrib.auth import views as auth_views from .forms import LoginForm from . import views app_name = 'account' urlpatterns = [ path('', auth_views.LoginView.as_view(template_name='shop/popup.html', redirect_authenticated_user=True, authentication_form=LoginForm), name='login'), ] <!-- Trigger/Open The Modal --> <button id="myBtn">Open Modal</button> <!-- The Modal --> <div id="myModal" class="modal"> <div class="modal-content"> <div class="modal-header"> <span class="close">&times;</span> <h2>Modal Header</h2> </div> <div class="modal-body"> {{ form }} {# <form>#} {# <div class="form-group col">#} {# <div class="col-xs-2">#} {# <label for="Email">Email address</label>#} {# <input type="email" class="form-control mb-6" id="Email"#} {# aria-describedby="emailHelp"#} {# placeholder="Enter email">#} {# </div>#} {# <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone#} {# else.</small>#} {##} {# <div class="col-xs-2">#} {##} {# <label for="exampleInputPassword1">Password</label>#} {# <input type="password" class="form-control mb-6" id="exampleInputPassword1"#} {# placeholder="Password">#} {# <div class="col-xs-2">#} {# </div>#} {# </div>#} {# </div>#} {# <button type="submit" class="btn btn-primary">Submit</button>#} {# </form>#} </div> <div class="modal-footer"> <h3>Modal … -
Google Search console seems unable to detect link to internal pages
My site Owly proposes a redesign of Wikipedia, and has potentially all Wikipedia’s pages in English. I use django i18 for internationalization. Google Search console shows that almost 90k pages are indexed, but the “link” report shows some unexpected data. In particular, only internal links to homepage are counted (60k more or less), but NO ONE of the links to internal pages are counted (es. to https://owly.wiki/Norway/). The same seems to be happening with external links. Has anyone idea of the reason? Has django internalization something to do with that? Thank you 🙏 -
Does the 'upload_to' callback in the FileField hit the db for related content?
I have an Attachment model with two ForeignKey fields and a get_attachment_path callback for the upload_to attribute.: def get_attachment_path(instance, filename): return f'{instance.owner.name}/{instance.chat.id}/{filename}' class Attachment(models.Model): owner = models.ForeignKey(..) chat = models.ForeignKey(..) file = models.FileField(upload_to=get_attachment_path, ...) This will make the get_attachment_path run: Attachment.objects.create(..., file=file) So, with the line above, will django hit the db twice (one for the .create and one another for the get_attachment_path)? Asking it because the get_attachment_path callback tries to access related data (instance.chat.id etc.). -
AlgoliaSearch: Sort items by score?
I've spent few days trying to figure out how can I sort items by a given configuration, for example we have a model that is called "Product". Product has "has_image" - boolean field, "rating" - decimal field. And I would like to sort the items in a way that: Only items with images should be in top also the second sort is rating, so the products should appear in desc order for the rating logic ("items that have the best rating"). I have created an index: @register(Product) class ProductIndex(AlgoliaIndex): custom_objectID = "pk" index_name = "Product" fields = ( "id", "title", "category_id", "category_ids", "slugified_attrs", "seller_id", "supplier_id", "rating_count", "has_image", "is_on_sale", "supplier_priority" ) settings = { "minWordSizefor1Typo": 4, "minWordSizefor2Typos": 8, "hitsPerPage": 20, "maxValuesPerFacet": 100, "version": 2, "attributesToRetrieve": None, "unretrievableAttributes": None, "optionalWords": "None", "attributesForFaceting": get_attributes_for_faceting(), "attributesToSnippet": None, "attributesToHighlight": None, "paginationLimitedTo": 1000, "attributeForDistinct": None, "exactOnSingleWordQuery": "attribute", "ranking": [ "typo", "geo", "words", "filters", "proximity", "attribute", "exact", "custom", ], "separatorsToIndex": "", "removeWordsIfNoResults": "none", "queryType": "prefixLast", "highlightPreTag": "<em>", "highlightPostTag": "</em>", "snippetEllipsisText": "", "alternativesAsExact": ["ignorePlurals", "singleWordSynonym"], "searchableAttributes": ["title"], "numericAttributesForFiltering": None, 'attributesForFaceting': [ 'filterOnly(has_image)', 'filterOnly(rating_count)', 'filterOnly(supplier_priority)', ], } And specified the attributesForFaceting for filters to work, but as I specify this search: params = { "hitsPerPage": settings.PRODUCTS_PER_PAGE, "optionalFilters": [ "rating_count<score=5000>", … -
How to build a vote option logic with two choices in Django
I have a Poller object/model that contains questions, each having two possible choices to vote for. Now I want to enable the user to vote for either of them. I thought to add two vote fields to the Poller model itself but then I wouldn't be able to figure out which user voted, right? That's why I decided to set up a Vote model to be able to link each vote to both a User and a Poller. However, this leads to my following two issues: I am not sure how to render the Vote form, since it contains two boolean fields only. My idea is to simply create two html divs containing the choice_fields of Poller model and trigger an ajax call as soon as a user clicks on one of the two choices to vote (so I wouldn't render the Vote Form at all) Doing so, I am not sure how to handle this logic in the view. My idea is to change the boolean field of the choice that was selected to True and the other to False (in case the users changes his vote from Foo to Bar). Vote Model and Form class Vote(models.Model): poller = … -
How to query contents(posts/videos) of people, a user follows with Django ORM when the user's details and following list is in separate database
Hey guys I recently starting working on a project where there are two different databases for storing user information and all the posted contents. I want to fetch and show, the contents posted by users who are in current user's following list. If this was in a single database, I could use a join statement like this, current_user = self.request.user.id following_ids = self.request.user.following.values_list('id',flat=True) posts = Content.objects.filter(Q(user_id__in=following_ids) | Q(user__id=current_user)) but since we use two different databases, how can I execute a similar query to show the contents. Please do help. Thanks -
Updating content of django-mezzanine web-page with psql/pg_read_binary_file corrupts the bage content
I'm new with django/mezzanine/postgres, thus could you help to figure out what is wrong in my procedure: dump content of the custom page: postgres# \o <absolute_path_to_my_working_directory>/<myFile.txt> postgres# select content from <myCustomPage> where page_ptr_id=<myPageId>; store the (modified or unmodified) content back to the custom page: postgres# update <myCustomPage> set content=pg_read_binary_file('./<myFile.txt>') where page_ptr_id=<myCustomPageId>; So when I got the page <myserver>:<myport>/admin/page_types/<myCustomPage>/<mypageId>/ I can see only \x followed by hundreds of 20. If I look at the the dumped myFile.txt with a text editot I can see every line finished by \r, which also looks strange and hints to some eol-character conflict as if the EOL-character encoding from ms-dos to unix had failed. -
How do you search for icons on aws server that has become yarn build?
enter image description here The codes created in vue have been built in django and are running on the aws server. You can see icon well on http://localhost:8080/ enter image description here However, an error of 404 appears on the aws server. enter image description here enter image description here Is there a wrong route? -
How to catch an error of creating chat room with two similar users?
I am trying to create chat room instance in database. I need to catch an error when room with two similar users is creating. Here is my chat-room models.py: class UserRoom(models.Model): class Meta: unique_together = ('user_one', 'user_two') room_id = models.UUIDField(default=uuid.uuid4, primary_key=True) user_one = models.ForeignKey('user.User', models.CASCADE, related_name='rooms_one') user_two = models.ForeignKey('user.User', models.CASCADE, related_name='rooms_two') def __str__(self): return f'{self.user_one} | {self.user_two} - {self.room_id}' serializer.py: def create(self, validated_data): user_one = self.context.get('request').user user_two = validated_data['user_two'] room = UserRoom.objects.create(user_one=user_one, user_two=user_two) message = ChatMessage.objects.create( chat_room=room, sender=user_one, text=validated_data['message'] ) return room views.py: @action(methods=['POST'], detail=False) def create_chat(self, request): serializer = CreateChatSerializer(data=request.data, context=self.get_serializer_context()) serializer.is_valid(raise_exception=True) a = serializer.save() return Response( UserRoomsSerializer(a, context=self.get_serializer_context()).data ) Also, I need an exception of creating existing room. -
Django: How can I filtering a foreign key of a class in models from users.forms
I create a Patient model in patient app from django.contrib.auth.models import User # Create your models here. class Patient(models.Model): doctor = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) sex = models.CharField(max_length=20) phone = models.IntegerField() birth_date = models.DateField() I want filternig the doctor fields wich is foriegn key from Users for just groups='Docteur', so when I want to add a patient I can find the users with 'Docteur' groups only not the other account's group. This is the forms.py in users app: from django import forms from django.contrib.auth.forms import UserCreationForm import datetime class RegisterForm(UserCreationForm): BIRTH_YEAR_CHOICES = [] for years in range(1900,2021): BIRTH_YEAR_CHOICES.append(str(years)) sex_choice = [('1', 'Men'), ('2', 'Women')] groups_choice = [('1','Docteur'), ('2','Docteur remplaçant'), ('3','Secrétaire')] first_name = forms.CharField(max_length=200) last_name = forms.CharField(max_length=200) sex = forms.ChoiceField(widget=forms.Select, choices=sex_choice) date_of_birth = forms.DateField(widget=forms.SelectDateWidget(years=BIRTH_YEAR_CHOICES)) email = forms.EmailField() phone = forms.IntegerField() cin = forms.IntegerField() groups = forms.ChoiceField(widget=forms.Select, choices=groups_choice) password1 = forms.CharField(widget=forms.PasswordInput(), label='Password') password2 = forms.CharField(widget=forms.PasswordInput(), label='Repeat Password') class Meta(UserCreationForm.Meta): fields = UserCreationForm.Meta.fields + ('username','first_name','last_name','sex','date_of_birth','email','phone','cin','groups') So what I suppose to do to add this condition. -
How can I get user id and multiselect field values in Admin.py file in
I want to change view site Url in Admin Panel like by default its directing to login page but I want to direct it "/select_ott" if user have two subscription else "/home" page, here subscription is multiselect Field I can use admin.site.site_url="/home" -
Alert of unsaved changes appears when I don't want to
I'm using django and I have some modal forms and buttons (which leads to other urls) and in all except one of the buttons it keeps appearing the alert of unsaved changes. I have tried to prevent it with window.onbeforeunload and various returns: return; return null; return void(0); but doesn't seem to patch my problem. I wanted to ask what should I look for in my code to search what could be the source causing this alert to appear, the only submits I have are on the modals -
Creating users through Admin in Django Rest framework
I am building a Cross-platform mobile application Mobile learning management system using React native and django Rest framework, where stakeholders are admin, instructor, and students. I want to have the functionality of creating user through only admin. Or maybe can have some mechanism that needs approval upon signup/registration of users from admin to access the app. I am really new to this field, guidance will be appriciated. -
How can I update nested serializer data in django rest framework?
Hii I am new to django rest framework,I want to perform update operation on nested serialized data but unable to complete it.Someone please look into it and suggest me so that it can be solve.Thank you My Models are: class MyUser(AbstractUser): bio = models.CharField(max_length=500, blank=True) is_younger = models.BooleanField(default=False) friends = models.ManyToManyField('self',blank=True, related_name="friends") class Profile(models.Model): genders = [ ("M", "Male"), ("F", "Female"), ] user = models.ForeignKey(MyUser, on_delete=models.CASCADE) age = models.IntegerField(null=True) gender = models.CharField(max_length=1, choices=genders) contact = PhoneField(blank=True, help_text='Contact phone number') address = models.CharField(max_length=100, blank=True) profilepic = models.ImageField(upload_to="profile/", db_index=True, default="profile/default.jpg") def __str__(self): return self.user.username ----Serializers are: class UsersProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' class ListUsersSerializer(serializers.ModelSerializer): profile = UsersProfileSerializer( read_only=True, many=True, source='profile_set') class Meta: model = MyUser fields = ['id', 'username', 'email', 'is_younger', 'friends', 'profile'] def update(self, instance, validated_data): profiles_data = validated_data.pop('profile') profiles = (instance.profile).all() profiles = list(profiles) instance.bio = validated_data.get('bio', instance.bio) instance.save() for profile_data in profiles_data: profile = profiles.pop(0) profile.contact = profile_data.get('contact', profile.contact) profile.address = profile_data.get('address', profile.address) profile.save() return instance Below is View code: class CheckUserDetailsViewSet(viewsets.ViewSet): permission_classes = [AllowAny] queryset = MyUser.objects.all() def list(self, request): serializer = ListUsersSerializer(self.queryset,many=True) return Response(serializer.data) def retrieve(self, request,pk=None): user = generics.get_object_or_404(self.queryset,pk=pk) serializer = ListUsersSerializer(user) return Response(serializer.data) I know ,I should create a update method … -
How do I match input password (api) to django admin password?
I am not doing authentication here I am just getting the user for sending OTP. I am taking email and password to validate but my password not converting to the algorithm if I enter 'a' then it will match it with Django stored hashers password. Thanks -
vue + webpack: how the dynamic component import works?
I use combination of Django+Vue, and I struggle to understand how do names that are created by vue-cli-service build or vue-cli-service serve are created and work, and how to set this in production. If I do not have dynamic component imports, everything works smoothly. My vue.config.js looks like that: module.exports = { pages: { main: { entry: "./src/main.js", chunks: ["chunk-vendors"], }, }, // Should be STATIC_URL + path/to/build publicPath: "/front/", // Output to a directory in STATICFILES_DIRS outputDir: path.resolve(__dirname, "../_static/front/"), // Django will hash file names, not webpack filenameHashing: false, productionSourceMap: false, runtimeCompiler: true, devServer: { writeToDisk: true, // Write files to disk in dev mode, so Django can serve the assets }, }; The result of built looks like that: And I simply refer to these files in a Django template: <div id="app"></div> <script type="text/javascript" src="{% static 'front/js/chunk-vendors.js' %}"></script> <script type="text/javascript" src="{% static 'front/js/main.js' %}"></script> But as soon as I start using dynamic components, like that: const User = () => import("./components/User") Everything stops working, and in addition webpack creates some js files with hashed names in a static folder, and I can't figure out the logic (so I can't refer to them in the template. -
Dockerize Websockets, Channels
I have dockerized project, Now I implement the dashboard in the project using channels now my problem is that i don't know how to dockerize the channel part (weak docker knowledge) -
How to Set the DATABASE_URL environment variable
I am trying to host a django website in gcloud... i did some changes in settings.py file after adding the file its showing error DATABASES = {"default": env.db()} # If the flag as been set, configure to use proxy if os.getenv("USE_CLOUD_SQL_AUTH_PROXY", None): DATABASES["default"]["HOST"] = "127.0.0.1" DATABASES["default"]["PORT"] = 5432 after adding this code into settings.py file i am facing below error File "C:\Users\CHANDU\Downloads\Unisoftone\unisoftone\website\website\settings.py", line 99, in <module> DATABASES = {"default": env.db()} File "C:\Users\CHANDU\AppData\Local\Programs\Python\Python38-32\lib\site- packages\environ\environ.py", line 208, in db_url return self.db_url_config(self.get_value(var, default=default), engine=engine) File "C:\Users\CHANDU\AppData\Local\Programs\Python\Python38-32\lib\site- packages\environ\environ.py", line 281, in get_value raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable -
Sequence integrity check documents in mongodb & python
I have three documents from Transaction collection, in each document there are amount and walletCredit . I want to check that the sum of value of amount and walletCredit, shoud be the value of next one walletCredit . here is my documents: now I can do this but it is not complete: pipeline = [ { "$match": { "status": 1, "walletId": 1 } }, { "$group": { "_id": "$walletId", "total": {"$sum": "$amount"}, } } ] transPerWalletId = Transaction.objects.aggregate(*pipeline) for items in transPerWalletId: transactions = Transaction.objects(walletId=items['_id']) for transaction in transactions: tmp = transaction.walletCredit + transaction.amount can anybody help me? -
Creating sub-models for ModelForms
I am trying to set up a settings database for my app that will determine how the rest of the app is generated for each complex (based on their setting) However, each of these complexes have completely different settings for each financial document I need to generate. I currently have the below form structure: Which is structured like this: class SettingsClass(models.Model): Complex = models.CharField(choices=complex_list , max_length = 22 ,default='1' , unique=True) Trial_balance_Year_to_date= models.BooleanField(default = False) Trial_balance_Monthly=models.BooleanField(default = False) Income_Statement_Year_to_date=models.BooleanField(default = False) Income_Statement_Monthly=models.BooleanField(default = False) Age_Analysis=models.BooleanField(default = False) Balance_Sheet=models.BooleanField(default = False) Repair_and_Maintenance_General_Ledger=models.BooleanField(default = False) Mayor_capital_Items_General_Ledger=models.BooleanField(default = False) def __str__(self): return (self.Complex + ' Settings') I would however like to add each of the financial documents settings to this form as well, for example: >**Complex Name** >**Trial Balance YTD** >> Include Opening Balances? >> Use only main accounts? >> Include 0.00 Accounts? >**Trial Balance Monthly** >> Include Opening Balances? >> Use only main accounts? >> Include 0.00 Accounts? >**Income Statement** >>Print YTD Value? >>Sort by Account name? Then the program reads these settings + sub-settings to create the documents needed. Is this possible with Django ModelForms and where can I find documentation etc. on how this is done?