Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Model instances saved only partially
I have a fairly complex view with several subforms and formsets with both many-to-many and one-to-one relationships. When getting a form from context object, I'm hitting a weird issue that some of the data is not saved. Correct model instance is created with form.save(), I can see all the fields I filled out in form, but all that's added to the database is pk, all the fields are empty. The same happens when I'm saving with commit=False and then saving again, when I'm updating fields manually and then saving or when I'm using force_insert=True. Creating new instances in the same code block however are saved without an issue. This doesn't end here, when saving many-to-many relationships, child models are saved without a hitch, but most of the time, m2m through models are not created. I said most of the time, because every once in a while they are. But even if they're not, the id descriptor in database is incremented so what I'm seeing in the through table is few lines, much less than there should be with non-sequential id-s. What am I dealing with here, does anybody have a clue? I'm out of ideas what to try next. I … -
Django allauth Automatically set mail address as confirmed
I am using django-allauth together with an LDAP-backend. So whenever a users logs in, the mail address is set to the mail address stored in our directory server. I was able to disable email confirmation by setting ACCOUNT_EMAIL_VERIFICATION = "none" But now those users have an unconfirmed mail address attached to their account. More specifically: I am trying to set up a mailman 3 including webUI and connect that to LDAP. Users having the mail address unconfirmed, causes them to not be able to use this address to subscribe to mailing lists. Can I maybe somehow modify the AccountAdapter to automatically confirm mail addresses when a user logs in? -
websocket connection in new_web.js not triggering consumers in django
the new.js file which contains the websocket connection and which actually connects/activates the django channels isn't connecting i don't understand where exactly the issue i have tried connecting another socket connection for different consumer in different html page that is working perfectly fine WebSocket HANDSHAKING /new/ [127.0.0.1:61934] WebSocket CONNECT /new/ [127.0.0.1:61934] Add specific.bYAxHTPf!sBbGasUiKdHR channel to post's group connected one websocket is connecting perfectly fine where as when i fireup localhost:8000/w which is supposed to connect the other websocket its not connecting that to consumers HTTP GET /static/js/channels/new_web.js 304 [0.01, 127.0.0.1:62085] i can access the websocket connection within the template but this websocket is triggering my path in routing which in turn triggers my consumers new_web.js $(function(){ endpoint = 'ws://127.0.0.1:8000/like/' // 1 var socket = new ReconnectingWebSocket(endpoint) // 2 socket.onopen = function(e){ console.log("open",e); } socket.onmessage = function(e){ console.log("message",e) var userData = JSON.parse(e.data) $('#new_user').html(userData.html_users) } socket.onerror = function(e){ console.log("error",e) } socket.onclose = function(e){ console.log("close",e) } }); socket.onclose = function(e){ console.log("close",e) } }); routing.py from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from django.urls import path from posts.consumers import PostConsumer,LikeConsumer application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( [ path("new/", PostConsumer), path("like/", LikeConsumer), ] ) ) }) consumers.py class LikeConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.user … -
Cannot Solve "ValueError: attempted relative import beyond top-level package"
I am running the project and shows this error. I have googled and tried some of the solutions but doesn't seem to work. File "/home/bs-094/Dev/backend/busgroup-backend/src/bus_portal_backend/apps/inquiry/forms/inquiry_details.py", line 2, in <module> from ..models.inquiry import Inquiry ValueError: attempted relative import beyond top-level package My folder structure is busgroup-backend src bus_portal_backend apps inquiry models _init_.py inquiry.py forms inquiry_details.py It would be great help is anyone helps me solve the problem. I am fairly new to django. Thanks -
Django REST Framework custom serializer mixin not working
I'm using Django 2.2 and Django REST framework. In the serializer, I want to have few fields only for creating an instance and not for updating. Means, the user won't be able to change the value of that field once created. Since Django does not provide any default way to do it. I am writing a mixin which when used will use the create_only_fields from the serializer Meta to remove the fields from the request data with PUT/PATCH request. serializer_mixin.py class CreateOnlyFieldsMixin(object): def to_internal_value(self, data): data = super().to_internal_value(data) print(data) if self.instance: # Update request print(data) for x in self.Meta.create_only_fields: if x in data: data.pop(x) return data and using in the serializer like class MySerializer(CreateOnlyFieldsMixin, serializers.ModelSerializer): class Meta: model = MyModel fields = [ 'id', 'name', 'value' ] create_only_fields = ['name'] But now calling any endpoint, it gives an error Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance. Putting CreateOnlyFieldsMixin after serializers.ModelSerializer gives no error but has no effect of the mixin. Appending to_internal_value directly in the serializer is working as expected. -
How to use a field value instead of pk in the url?
I want to show the username or name of the person I want to update details for, in the url of update view. The only method I know is to display pk in the url. Is there a method to replace pk with a field value? Thanks in advance. -
in update form when went to update profile picture getting MultiValueDictKeyError at /42/accountdetails 'picture'
In my app i have a details where user can view and update their details.I went to update profile pic and when i choose profile pic and click on update it returns MultiValueDictKeyError at /42/accountdetails 'picture' models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(upload_to='media',default="None") views.py def accountdetails(request,pk): user=User.objects.get(pk=pk) initial_values= {'Firstname':user.first_name,'Lastname':user.last_name, 'Username':user.username,'Email':user.email} if request.method == "POST": form = Accountdetails(request.POST,request.FILES) if form.is_valid(): email = form.cleaned_data['Email'] Username=form.cleaned_data['Username'] firstname=form.cleaned_data['Firstname'] lastname=form.cleaned_data['Lastname'] user=User.objects.filter(pk=pk).update(first_name=firstname, last_name=lastname,username=Username,email=email) pro=Profile.objects.filter(user_id=pk).update(image= request.FILES['picture']) messages.success(request,'Updated Successfully!') return redirect('accountdetails', pk=pk) else: form = Accountdetails(initial=initial_values) return render(request,'accountdetails.html',{'user': user,'form':form}) forms.py class Accountdetails(forms.Form): picture = forms.ImageField(required=False) #i am posting only for imagefield -
Django shorten query on save to ForeignKeyField
I have 2 models Owners, Relationships Owners class Owner(models.Model): id = models.BigAutoField(primary_key=True) nickname = models.CharField(max_length=20, unique=True) Relationships class Relationships(models.Model): id = models.BigAutoField(primary_key=True) owner = models.ForeignKey(Owner, on_delete=models.CASCADE, related_name='relationship_owner') target_owner = models.ForeignKey(Owner, on_delete=models.CASCADE, related_name='relationship_target_owner') To add rows to Relationships, I used below query. owner1 = Owner.objects.filter(nickname='hide').first() owner2 = Owner.objects.filter(nickname='john').first() Relationships.objects.create(owner=owner1, target_owner=owner2) It is pretty clear. But when I inspect on django-debug-toolbar, it queried to database 3 times. Get nickname=hide from owners table. Get nickname=john from owners table. Insert into hide and john into relationship table. I wonder that, is it a general way? Or, Is there any clear way to performing above query? Thanks! -
How to make a login and signup page using an existing model in Django==2.1
I am a making a student management system with django. I have a Student model which should be modified only by the registrar when a student takes admission. The registrar will use the inbuilt django admin page to add students. class Student(models.Model): first_name = models.CharField(max_length=100, null=False, blank=False) last_name = models.CharField(max_length=100, null=False, blank=False) roll = models.CharField(unique=True, max_length=200, null=False, blank=False) email = models.EmailField(unique=True, null=False, blank=False) age = models.PositiveIntegerField(blank=True) gender = models.CharField(choices=GENDER, default='O', max_length=1) dob = models.DateField(null=False, help_text='YYYY-MM-DD', blank=False) admission_type = models.CharField(choices=ADMISSION_TYPES, default='B', max_length=1) Now I want to be able to use this model to make a login and signup page for students. In the signup page, the student enters his valid roll number and a password. In the login page he must enter this roll and password to go to his dashboard. How can I do this efficiently? I have tried extending AbstractUser but I am unable to make it work. -
How to display relationship with back reference at django template through User?
I have such models class Employee(models.Model): """Employee information.""" user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='employee', unique=True) position = models.CharField("current position in a company", max_length=64, blank=True) birth_date = models.DateField("date of birth", null=True) skills = models.ManyToManyField( Technology, through="Skill", verbose_name="skills", blank=True) class Technology(models.Model): """Technologies.""" name = models.CharField('technology name', max_length=32, unique=True) class Skill(models.Model): """Information about an employee's skills.""" LEVELS = ( ('basic', 'Basic'), ('intermediate', 'Intermediate'), ('advanced', 'Advanced'), ('expert', 'Expert'), ) employee = models.ForeignKey( Employee, on_delete=models.CASCADE, related_name="employee_skills") technology = models.ForeignKey(Technology, on_delete=models.CASCADE) start_date = models.DateField( verbose_name='Works with since:') level = models.CharField("level", max_length=64, choices=LEVELS) And I can't understand why my template code doesn't work template.html {{ user.employee.position }} {{ user.employee.birth_date }} {{ user.employee.summary }} {% for i in user.employee.skills.all %} {{ i.technology.name }} {{ i.level }} {% endfor %} I can't see absolutely nothing. All models possible to see at adminpanel. And else then I using TemplateView such as class AccountView(TemplateView): template_name = "profile.html" def get_context_data(self, **kwargs): context = super(AccountView, self).get_context_data(**kwargs) context['skills'] = Skill.objects.filter(employee__user=self.request.user) return context then everything works fine. -
Is there any ways to combine two rows of table into one row using Django ORM?
I have a table which has columns named measured_time, data_type and value. In data_type, there is two types, temperature and humidity. I want to combine two rows of data if they have same measured_time using Django ORM. I am using Maria DB Using Raw SQL, The following Query does what I want to. SELECT T1.measured_time, T1.temperature, T2.humidity FROM ( SELECT CASE WHEN data_type = 1 then value END as temperature , CASE WHEN data_type = 2 then value END as humidity , measured_time FROM data_table) as T1, ( SELECT CASE WHEN data_type = 1 then value END as temperature , CASE WHEN data_type = 2 then value END as humidity , measured_time FROM data_table) as T2 WHERE T1.measured_time = T2.measured_time and T1.temperature IS NOT null and T2.humidity IS NOT null and DATE(T1.measured_time) = '2019-07-01' Original Table | measured_time | data_type | value | |---------------------|-----------|-------| | 2019-07-01-17:27:03 | 1 | 25.24 | | 2019-07-01-17:27:03 | 2 | 33.22 | Expected Result | measured_time | temperaure | humidity | |---------------------|------------|----------| | 2019-07-01-17:27:03 | 25.24 | 33.22 | -
Understanding Django localization in templates
I am trying to use two languages in my website, my native, and an english one. I followed the django documentation, from where I copied the code. I have the locale folders and files set up. When I open the site, it already sets the default language to Slovene, which should be English instead, and I don't know why. The main.html looks like this when I open the site: <html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/html" xmlns:height="http://www.w3.org/1999/xhtml" lang="sl" > If I understand correctly, the lang="sl" should be lang="en", and I do not know why it defaults to Slovene. Even when I use the form, it shows me both choices (English and Slovene), but when I select English, and click Go, it just refreshes the page, but doesn't change the language. The current language (Slovene) still stays selected, so I'm guessing that somewhere the correct language doesn't get selected. I'm also confused as to why it doesn't default to English when I start the server. Can anyone provide some insight or point me in the right direction? settings.py LANGUAGE_CODE = 'en-gb' TIME_ZONE = 'Europe/Ljubljana' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ os.path.join(BASE_DIR, "locale"), ] ugettext = lambda s: s LANGUAGES … -
How do I add points of skill tags for every correct main questions and sub questions?
enter image description here consider a folder which contains main questions and subquestions. Teacher create those questions with skill tags( core skill, knowledge skill, exam skill, foundation skill). Now student is taking his exam, first he will get main question, if he do well we have to add the points to that main question. For suppose he did mistake the main question, we have to give sub questions which relates to main question it also has skill tags. If he do correct here we should add the points of main and subquestions. -
how to test django modal details?
i'd like to test this little part of code : @staff_member_required() def prestation_details_modal(request, uuid): p = get_object_or_404(Prestation, uuid=uuid) return TemplateResponse(request, "includes/modal /prestation_modal.html", {'prestation': p}) i ever tested something like : def test_resp_temp_page(self): url = reverse('index') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertTemplate(response, 'include/modal /mission_modal.html') thx for help ! -
Calling View in API Request Factory when testing in Django Rest Framework
Whenever we test an API in Django Rest Framework using API Request Factory why do we call the view when we are already passing the url . Look at the following code for better understanding . request = self.factory.post("/api/v1/menu/", data) views = MenuResource.as_view({"post": "post"}) response = views(request) response.render() self.assertEqual(201, response.status_code) In the above code we are calling the url as well as calling the view . View is being called for rendering the view on the url but that is not what my use case is . I just want to test the response code . Is there a way of getting the response code without rendering the view as that is an over kill for my use case . I have looked for other methods except for using API Request Factory but i just wanted to know why does API Request Factory need to call the view . Is there any advantage in comparison to other API Testing modules present in Django Rest Framework .enter code here -
How do I create a button for adding a time in the Django Form Template?
How do I create a button for adding a time in the Django Form Template? form is this class TodoForm(forms.ModelForm): dead_line = forms.SplitDateTimeField(widget=widgets.AdminSplitDateTime, initial=datetime.datetime.now()) class Meta: model = Todo fields = ['title', 'content','classification','dead_line'] widgets = { 'content': SummernoteWidget(), } form.html is this <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form | safe }} <button type="submit" class="btn btn-primary float-right btn-block">Submit</button> </form> result question : What if I want to create an hour button or an extra day button? Do I need to use a widget? Should I create a js button? Thank you very much for giving me specific examples. tanks for reading ~! -
I want to show a fixed value in a field in forms.py
I am making a model form for mock up website, asking for seller information. I want the field country to be fixed to a certain country and the seller cannot change it.Assuming the website do not operate in any other country. How can i show the field as fixed and not changeable showing a fixed country value ? This is my model form: class seller(forms.Form): gst_number = forms.CharField(label='GST-Number',max_length=100, validators=[GST_validator]) add_line_i = forms.CharField(label='Address Line 1',max_length=100) city= forms.CharField(required = True,widget = forms.Select(choices=indiancities)) country = forms.CharField(required = True) I am getting it like this : I want it to be like this and country should not be editable. -
How to keep track of history of transactions and rollback when needed?
Let's say I'm maintaining an Activity log of a user in UserActivity model. class UserActivity(models.Model): description = models.TextField() query = models.TextField() How to implement and what fields are required on this model, so that I would be able to rollback a transaction in history at any time? What are its cons and dependencies? I know transaction.atomic. Think of this as doing a transaction a few days ago and rolling back today. -
Tests fails after import external library
Hey I'm facing kind of weird problem. I have Django project with 3 applications: core mturk_manager cognito_admin The mturk_manager is the new one. When I run tests only for this application using command python manage.py test mturk_manager or even with core application together python manage.py mturk_manager core everythings passes as expected. Problem is with application cognito_admin when I run all tests together some of the tests from my new application mturk_manager fails. I was debugging the problem for such a long time :) and found problem: In cognito_admin I'm importing external package from moto library from moto import cognito_idp even if I have commented out all tests from cognito_admin tests still fails in other application. I really need this package its really usefull. Any ideas how to solve this problem ? -
Delete data form after sending post request
I'm coding user management page. In page, I have form to add new user with post request and delete button with comfirmation form. I add new user successfully, page is reloaded, then I delete any account, but data in form I sent request to create new user is sent again with new user ID. How to fix? -
Why post request is working on django 2.2.1 but in version 1.11.20 fails?
When I am trying to do a post request in my remote machine through the view file presented below I'm getting an HTTP 400 bad request, however, when I do the same using my local machine it works perfectly. Here are the most important details of each machine according to my understanding: Local machine django == 2.2.1 drf == 3.9.4 python == 3.7 Remote machine (Using docker on an EC2 machine) django == 1.11.20 drf == 3.9.4 python == 2.7 I've already check that drf 3.9.4 still compatible with python 2. https://www.django-rest-framework.org/community/release-notes/ views.py from django.shortcuts import render from django.http import HttpResponse from django.urls import reverse from .models import irrigation, moisture from .serializers import IrrigationSerializer from rest_framework import viewsets from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view, action class irrigationValues(viewsets.ModelViewSet): queryset = irrigation.objects.all() serializer_class = IrrigationSerializer def list(self, request): serializer = self.serializer_class(self.queryset, many = True) return Response(serializer.data) def dashboard(request): irrigations = irrigation.objects.all() return render(request, 'dashboard.html',{'irrigations':irrigations}) @api_view(['POST']) def addIrrigation(request): addIrrigation = IrrigationSerializer(data=request.data) if addIrrigation.is_valid(): addIrrigation.save() return Response({"data":"Value added"},status = status.HTTP_201_CREATED) else: error_details = [] for key in addIrrigation.errors.keys(): error_details.append({"field": key, "message": addIrrigation.errors[key][0]}) data = { "Error": { "status": 400, "message": "Your submitted data was not valid - please … -
What should be the broker url for redis on production mode in Django
When I'm trying to run my Django project on VPS, it works perfectly but the problem is Celery broker. on my local mechine I used this code on tasks.py and celery.py app = Celery('imgmanipulation', backend='redis', broker='redis://localhost') How should I change this for production uses? Suppose I've a hosting which is: id: root@167.78.250.252 pass: farid.19 Any type of help will be appreciated. Thank you :) -
python how to dump dynamic create class to file
I had been dynamic create a python meta class I want to dump it to a python file cls = type("ClsName", (object, ), attr) code = xxxGetSource(cls) writeToFile(code, "moduleName/ClsName.py") I need this, because when django makemigrations, it need to found the metaclass for model, but my model metaclass was dynamic generate class XXXModel(GenerateMetaCls({ .... }), models.Model): pass -
How to startup telegram bot in django correctly
I am trying to connect a telegram bot (webhook) to my project. In the project/tbot.py I have method tbot_startup(): dp = DjangoTelegramBot.dispatcher dp.add_handler(CommandHandler("start", tbot_hello)) logger.info('TELEGRAM BOT STARTED') In the file, wsgi.py: application = get_wsgi_application() tbot_startup() # It doesn't matter before or after the "application" var After launching the application (manage.py runserver), there is an entry in the log: IndexError: list index out of range It's about this line: https://github.com/JungDev/django-telegrambot/blob/master/django_telegrambot/apps.py#L47 I've tried to fix it, with this code. bot = DjangoTelegramBot bot.bot_tokens.append(TOKEN_FROM_SETTINGS) dp = bot.dispatcher dp.add_handler(CommandHandler("start", tbot_hello)) Now the application starts, but the bot does not work. At the same time, if you change something in the project, django will re-read the files and the bot will restart and work. I don't know how to fix it. Please, help me startup bot with main web-application correctly. -
I am not able to load the staticfiles in my templates. What am I doing wrong?
I need to incorporate css in my templates to help them look better, but inspite of adding the static url and root, I am just not able to load it in my template. I am attaching the relevant code here. Please tell me what am I doing wrong. Thanks in advance. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATIC_ROOT = [STATIC_DIR,], index.html <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <link href="{% static 'css/index.css' %}"> </head>