Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
I can't get my models to serialize properly using Django DRF but they do in Admin
I am absolutely at my wits end! I can't for the life of me work out why my serialization isn't working properly. Two problems; the first is that I can't populate the Employee and Business ForeignKey fields for the Bookings serializer in the DRF API view but can on the admin side. I did get to a point where it was showing something relative to the ForeignKey but error of list not accepted and no actual field; it wasn't right regardless. Even when I try to view the raw data the foreign keys are not there as any type of input option. This problem was noticed when I was trying to override perform_create() and create() methods - tried so many different variations and finally realised that the methods weren't even getting called print('create is being executed') unless I explicitly made the serialzer field read_only. I'm hoping the reason why perform_create() and/or create() weren't firing because the serializer isn't even populating a field for me to manually enter data for the ForeignKeys; let alone in a another method. I've simplified the models, serializer and view to only include the necessary objects/methods; please let me know if I need to share anything … -
Reciprocation Of Django Model ForeignKey
I want to reciprocate the existence of my ForeignKey in the Client app. Client App Structure: Project Client model.py Client model.py Code: class Client(models.Model): primary_key = models.AutoField(primary_key=True) unique_num = models.TextField(max_length=30) name = models.TextField(max_length=30, default='Name Not Found') number = models.TextField(max_length=30) email = models.EmailField() Email App Structure: Project Email model.py Client model.py Code: class ScheduledEmail(models.Model): primary_key = models.AutoField(primary_key=True) recipient_name = models.TextField() subject = models.TextField() message = models.TextField() datetime_sent = models.TextField(max_length=20, default='Not Yet Sent') datetime_created = models.TextField(max_length=20) recipient_email = models.EmailField(max_length=50, default='Email Not Found') sent = models.BooleanField(default=False) recipient = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='scheduled_emails_sent') -
can you explain this python django makemigrations error?
i deleted my database and when i tried to migrate with a new database i am getting this error. traceback File "D:\work\Student Management\student_management_system\student_management_app\urls.py", line 3, in <module> from . import views, AdminViews, StaffViews, StudentViews File "D:\work\Student Management\student_management_system\student_management_app\views.py", line 7, in <module> from .AdminViews import * File "D:\work\Student Management\student_management_system\student_management_app\AdminViews.py", line 4, in <module> from .forms import * File "D:\work\Student Management\student_management_system\student_management_app\forms.py", line 8, in <module> class AddStudentForm(forms.Form): File "D:\work\Student Management\student_management_system\student_management_app\forms.py", line 19, in AddStudentForm for course in courses: File "D:\work\Student Management\myvenv\lib\site-packages\django\db\models\query.py", line 280, in __iter__ self._fetch_all() File "D:\work\Student Management\myvenv\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "D:\work\Student Management\myvenv\lib\site-packages\django\db\models\query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "D:\work\Student Management\myvenv\lib\site-packages\django\db\models\sql\compiler.py", line 1175, in execute_sql cursor.execute(sql, params) File "D:\work\Student Management\myvenv\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "D:\work\Student Management\myvenv\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "D:\work\Student Management\myvenv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "D:\work\Student Management\myvenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "D:\work\Student Management\myvenv\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "D:\work\Student Management\myvenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "student_management_app_courses" does not exist LINE 1: ...student_management_app_courses"."updated_at" FROM "student_m... i dont understand what the error is can somebody please … -
How link Noscript tag in Django python
I try to linked CSS in my html , but not working what is issue? others working <link rel="stylesheet" href="{% static "/player/css/appf6eb.css" %}"> <link rel="preload" href="{% static "/player/themes/qartulad/assets/css/fonts.css" %}" as="style" onload="this.onload=null;this.rel='stylesheet'"> <noscript><link rel="stylesheet" href="{% static "/player/themes/qartulad/assets/css/fonts.css" %}"></noscript> <link rel="preload" href="{% static "/player/themes/qartulad/assets/plugins/fontawesome-free-5.6.3-web/css/all.min.css" %}" as="style" onload="this.onload=null;this.rel='stylesheet'"> <noscript><link rel="stylesheet" href="{% static "/player/themes/qartulad/assets/plugins/fontawesome-free-5.6.3-web/css/all.min.css" %}"></noscript> <link rel="stylesheet" href="{% static "/player/themes/qartulad/assets/css/style-mixed434d.css" %}"> -
how do i filter from variant that is many_to_many relationship with category
Here is my code: # VIEW.PY def retrieve(self, request, pk=None): variant_id = request.get('variant_id') queryset = Category.objects.filter(category_id=pk) querysetSerializer = CategoryServiceListSerializer(queryset, many=True) i want to filter variant_id from Variant so that it display only that particular variuant. Not sure where changes need to be made in views or serialzier. im assuming this could be solution queryset = Category.objects.filter(category_id=pk,variant__in = variant_id) but getting error TypeError: 'int' object is not iterable # MODELS.PY class Category(models.Model): category_id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=50) category_icon = models.CharField(max_length=500, null=True, blank=True) category_image = models.CharField(max_length=500, null=True, blank=True) category_description = models.CharField(max_length=1000, null=True, blank=True) active_status = models.BooleanField(default=True) class Variant(models.Model): variant_id = models.AutoField(primary_key=True) service_id = models.ManyToManyField(Services) category_id = models.ManyToManyField(Category) variant_name = models.CharField(max_length=100) variant_icon = models.CharField(max_length=1000, null=True, blank=True) variant_image = models.CharField(max_length=1000, null=True, blank=True) variant_description = models.CharField(max_length=5000, null=True, blank=True) active_status = models.BooleanField(default=True) # SERIALIZER.PY class CategoryServiceListSerializer(serializers.ModelSerializer): variant = VariantServiceSerializer(many=True, source="variant_set") class Meta: fields = "__all__" model = Category class VariantServiceSerializer(serializers.ModelSerializer): class Meta: model = Variant fields = "__all__" -
interagtion of scrapper.py to flask
i made a web scrapper which loads the data in dataframe as df everytime i run the program. is there a possible way in which i can integrate this data frame i.e df in flask or web app and to save he data in a database (sql) ?? regards -
com_error when trying to get COM object with win32com.client from Django view
I am trying to connect a SAP GUI session to my Django project so I can interact with it, by using win32com.client to work with COM objects. When working from the shell I have no problem at all to get this working by running the following code: sap_gui = win32com.client.GetObject("SAPGUI") application = sap_gui.GetScriptingEngine connection = application.Children(0) session = connection.Children(0) If I start the server with this code in the views.py Django module this also works, and I can get the session info displayed in my Django view. However, I want to be able to connect and disconnect such session by hand, since different users will need to connect to different sessions, and by running the code at start I can only stick to the first session. I have been trying to get this working by defining the following view in views.py: def dashboard(request): if request.method == 'POST' and 'SAP_button' in request.POST: # Get the COM object (SAP session in this case) sap_gui = win32com.client.GetObject("SAPGUI") # ERROR HERE application = sap_gui.GetScriptingEngine connection = application.Children(0) session = connection.Children(0) # This is just a test to see if I get the desired output from the COM object test = session.info.User return render(request, 'Users/dashboard.html', … -
Reverse for '' with arguments '('',)' not found
I am trying to implement a way to change some saved settings on my app , the user should be able to view and change these settings accordingly. However , the above error is received when trying to load the "SettingsHome" page. Please see the below code and full error message: Error: NoReverseMatch at /settings Reverse for 'viewSettings' with arguments '('',)' not found. 1 pattern(s) tried: ['accConnect/setting/(?P<settings_pk>[0-9]+)$'] Request Method: GET Request URL: http://localhost:8000/settings Django Version: 3.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'viewSettings' with arguments '('',)' not found. 1 pattern(s) tried: ['accConnect/setting/(?P<settings_pk>[0-9]+)$'] Exception Location: C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.4 Python Path: ['C:\Users\KylePOG\Documents\GMA Programming\accConnect', 'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39', 'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Tue, 14 Sep 2021 08:30:03 +0000 Error during template rendering In template C:\Users\KylePOG\Documents\GMA Programming\accConnect\main\templates\main\base.html, error at line 7 Reverse for 'viewSettings' with arguments '('',)' not found. 1 pattern(s) tried: ['accConnect/setting/(?P<settings_pk>[0-9]+)$'] 1 2 3 4 5 /* The sidebar menu / 6 .sidenav { 7 height: 100%; / Full-height: remove this if you want "auto" height / 8 width: 160px; / Set the width of the sidebar / 9 position: fixed; / Fixed Sidebar (stay in place on scroll) / 10 z-index: 1; / … -
NoReverseMatch at /polls/3/vote/
So I've tried to check for an answer to similar questions asked but I haven't found one that solves my problem. I could be wrong but from my understanding, my code isn't reading my question.id, which means nothing is being passed to my vote view. Here's the code snippet: My views: My URLs: And the form where question.id is being passed to polls:vote from: Here is the error I'm encountering: Again, my bad if the question has been answered before but I had to be sure. Can anyone point out what I'm missing? -
Django how to create a filled update object form?
I want to create an update form. When a user enters this page the form should be filled with information so that the user can edit what they want to fix. I try to use instance in views but didn't work. The fields are still empty. How can I do it? views.py def setup_settings(request): user = request.user data = get_object_or_404(DashboardData, user=user) # print(data) --> DashboardData object (45) form = SetupForm(request.POST or None, instance=data) if request.method == 'POST': if form.is_valid(): form.save() else: form = SetupForm() context = { 'form': form, } return render(request, 'update_setup.html', context)