Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django formset is_valid fails Cannot assign "u'username'": "contact" must be a "User" instance
I have a django inline formset that populates a bunch of forms. One of the field is a contact entry which would a be user name. User can select the user name and data is sent in Post call. Problem is the formset.is_valid call fails because of the error. I specifically converted the contact value in request object to specified user object but Django somehow later again converts it a unicode string and i get the error. Not sure whats happening here. Model: class ATest(models.Model): contact = models.ForeignKey('auth.User', related_name='test_contact', null=True, blank=True) View (Post Call): request.POST['atest-0-contact'] = GetOrCreateUserMixin.get_or_create_user(request.POST['atest-0-contact']) ctx['formset_test'] \ = formset_test \ = TestAFormSet( request.POST, instance = test ) is_valid = formset_test.is_valid() Form: class ATestForm(forms.ModelForm, GetOrCreateUserMixin): contact = forms.CharField( label='Contact', widget=forms.TextInput(attrs={ 'autocomplete': 'off', 'class': 'js-widget-user-typeahead', 'style': 'width: 95%' }), # help_text='Begin typing user name', required=False ) class Meta: model = models.ATest fields = ( 'contact', ) def __init__(self, *args, **kwargs): self.conflict = {} self.user = kwargs.pop('user') super(ATestForm, self).__init__(*args, **kwargs) self.original = {} self.fk_display_fields = ( # contact, ) if contact in self.fields: self.fields[contact].help_text = '' self.fields[contact].label = '' def clean_contact(self): if not self.cleaned_data[contact]: return None return self.get_or_create_user(self.cleaned_data[contact]) TestAFormSet = inlineformset_factory(models.Test, models.ATest, form=ATestForm, formset=BaseAutomationFormSet, extra=0, help_texts=None, labels=None, can_delete=True) -
Docker & Python, Speed up when your requirements.pip list is huge?
Say you have a rather large requirements.pip when you modify a requirements.pip, it takes ages to build Docker image because it has to download and install all packages in requirements.pip Is there a way to speed up the docker image building process when you modify a length requirements.pip ? -
How to prevent save() from update created timestamp
My django app has a table with a datetime field date_created, which is set default to CURRENT_TIMESTAMP. The database is MySQL. When I update a record to change a certain field (say, rank). I did the following: >>> from orchiddb.models import HybImages >>> >>> id = 39387 >>> image = HybImages.objects.get(pk=id) >>> image.date_created datetime.datetime(2019, 5, 24, 15, 28, 29, tzinfo=<UTC>) >>> image.rank = 1 >>> image.save() >>> image.date_created datetime.datetime(2019, 10, 31, 14, 14, 51, 852406, tzinfo=<UTC>) Why did the date_created value changed (and what 852406 stand for)? What do I have to do to keep date_created unchanged? -
Problem when creating a form with both django-autocomplet-light and and bootstrap-datepicker-plus widgets
I am trying to create a form which uses two different widgets: - some fields are using django-automplete-light ModelSelect2 widget - another field is using bootstrap_datepicker_plus DatePickerInput widget However, I can't manage to make them both work: when I create a form with DatePickerInput only, the calendar shows correctly, but when I add fields using ModelSelect2, the calendar doesn't popup anymore. Does anybody know what could cause this problem and how to solve it? In settings.py I set 'include_jquery' = True for BOOTSTRAP4 Below is an extract of the form code: from django.forms import ModelForm from dal import autocomplete from bootstrap_datepicker_plus import DatePickerInput class CreateWhoForm(ModelForm): class Meta: model = m.Who fields = ( 'why', 'how', 'begins' ) widgets = { # when 'why' and 'how' are commented, DatePickerInput() calendar widget shows correctly # when they are present, the calendar widget doesn't show anymore 'why': autocomplete.ModelSelect2( url='core:why-autocomplete' ), 'how': autocomplete.ModelSelect2( url='core:how-autocomplete' ), 'begins': DatePickerInput() } And some of the html used: <pre> {% load static %} {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {{ form.media }} {% for field in form %} <div class="form-group{% if field.errors %} has-error{% endif %}"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {% … -
Add sitemap on external server to Django Sitemap
Django has a built-in Sitemap class to generate a sitemap.xml from the urls it contains (well - the user has pointed to). That's great. But my blog to my web app (which is on e.g. mysite.com) is hosted on a different server and run using WordPress. The blog URL is blog.mysite.com. My question is: is there a way to use the django built-in sitemap class to add this external url (blog.mysite.com) to the generated sitemap.xml? If not - what is the best way to create the sitemap file? Wordpress also generates a sitemap on its own, so I need a reference in the django generated sitemap.xml pointing to the WP sitemap.xml. But how to link those two? -
Correct Displaying Django Forms
I`ve stacked w problem that i wrote similar code for 2 html pages on my website First page is situated on 127.0.0.1 and second is on 127.0.0.1/accounts/signup Browser parsing it and getting the same code from the 2 files gives 2 different answers 127.0.0.1 has no such code in generated html file <p><label for="id_email">Email:</label> <input type="email" name="email" placeholder="EmailAddress"id="id_email"></p> <p><label for="id_password1">Password:</label> <input type="password" name="password1" placeholder="Password" required id="id_password1"></p> But 127.0.0.1/accounts/signup has How to fix it, i need my forms on 127.0.0.1 What i`ve 2 do ? -
why am I getting previous django project's css instead of current django project?
I made static directory inside my app and kept my css folder inside static with the name style.css. I set the css link as : <link rel="stylesheet" href="{% static 'css/style.css' %}"> I think all the path is correct but it shows the previous project's css. why this is happening? -
Django Invalid column name with SQL Server, but query works in the shell
I'm trying to make this work in django. I'm using django_filters and django ORM for the query. The query doesn't show any errors when i run it in the shell, but when i do python manage.py runserver, I get this error in the browser: ('42S22', "[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'ARecordID'. (207) (SQLExecDirectW); [42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") When I use ARecordID in a raw sql query it works, but I don't want to work with raw queries since I want to be able to use django_filters. This is what I have(changed field names and model names to make things easier(relatively)): models.py: class modelA(models.Model): arecordid = models.IntegerField(db_column='ARecordID', primary_key=True) # Field name made lowercase. name = models.CharField(..) .. class modelB(models.Model): a = models.ForeignKey('modelA', db_column='ARecordID', on_delete=models.CASCADE, db_constraint=False) number = modelsIntegerField(..) .. views.py: a_list = modelB.objects.select_related('a').filter(number=5).values('a__arecordid', 'a__name', 'number', 'phone') filter = aFilter(request.GET, queryset = a_list) return render(request, "template.html", {'filter': filter}) template.html: {% block content %} <form method="get"> {{ filter.form.as_p }} <button type="submit">Search</button> </form> <table> {% for obj in filter.qs %} <tr> <td>{{ obj.number }}</td> <td>{{ obj.a.name }}</td> </tr> {% endfor %} </table> {% endblock %} Any help is appreciated! -
How can I go back a migration on Django?
I put accidentaly a default value 'string' to an integerfield on the migration, now I've been having problems with that, how can I go back to the previuosly migration or delete this field? ValueError: invalid literal for int() with base 10: 'modulo' -
Django making field related to other field (object) value
few years ego I worked with Odoo framework. and Odoo has very nice feature like this: partner_id = field.Many2one(Partner) partner_name = fields.Char(string='Partner name', related='partner_id.name') basically whenever you would assign different partner_id from Partner table, partner_name would be assigned automatically. Now I started to work with django (absolute newbie), and I can't seem to find a similar functionality. My question is what could be possible solution for this problem. Maybe there are already established external libraries that has this sort of functionality? Expected result: product = models.ForeignKey(Product) product_color = models.CharField(string='Partner name', related='product.color') having in mind that product object would have color field and it would be assigned to product_color whenever product field value Product object color value changes. Also what about storing it to database? Would be nice if there was an option to chose between storing it in database or getting it on the fly. Cheers! -
DRF - adding depth=1 to serializer messes up with object creation
I have a simple serializer: class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = [field.name for field in model._meta.fields] # depth = 1 extra_kwargs = {'created_by': {'default': serializers.CurrentUserDefault()}} Which works both ways - I can list Orders and I can create an Order. As you see there is created_by set to default user which works without specifying depth. When I specify depth when creating an object, DRF returns error: null value in column "created_by_id" violates not-null constraint I know that it's because now, the created_by is serialized as user but don't know how to make it work when creating objects. -
Internal server error during when I output serializer data as response in view
In my model, I add a foreign key to auth_user of django's default user class: class MyModel(models.Model): managed = True db_table = 'myTable' user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) .... In my view, I try to limit the list result with the active user. class MyView(viewsets.ModelViewSet): def list(self, request): # Get active user: user = self.request.user # Create a customized query set: queryset = MyModel.objects.filter(user=user) # Build serializer: serializer = MyModelSerializer(queryset, many=False) # Return response: return Response(serializer.data) MySerializer is as follows: class MyModelSerializer(serializers.ModelSerializer): user = serializers.RelatedField(source='user', read_only=True) class Meta: model = MyModel fields = ('id') # or any other field in the model. But this outputs a 500. When I try to output user.id, it outputs user id successfully. Response(user.id) # Returns 1. What am I missing? -
Premature field validation in Django migrations
I have the following issue: I work on a Django app that has a primary DB and now we are adding a secondary DB for syncing only some of the data in it. When I tried to run the migrations, I got an error: null value in column 'field_3' violates not-null constraint. And here is the issue: The model: class A(models.Model): field_1 = models.BooleanField(default=False) field_2 = models.BooleanField(default=True) # added later field_3 = models.BooleanField(default=True) # added later and 4 migrations (well, more, but those don't count): 0001 - a related model is created 0002 - model A is created and the relation is created (ForeignKey) 0003 - field_2 is added to model A 0004 - field_3 is added to model A However when I run migrate on the new DB, the migration stops at migration 0002 with the error mentioned above: django.db.utils.IntegrityError: null value in column "field_2" violates not-null constraint even though the field is created in a later migration. I don't know hot to even begin a workaround this issue. -
Best way to schedule tasks on dates
Consider a scenario where I have the following: - Users - Powers - Eligible In my Power model, I gave the superuser the ability to create custom powers and among those options to create the power, there's a field where the they can choose an eligibility date for when those powers are available to the User. That's fairly simple, but, I also have an other model called Eligible which looks like this: class Eligible(models.Model): user = models.ForeignKey(User, on_delete=blahblah) power = models.ForeignKey(Power) eligible = models.BooleanField() When I create a User, link the Power to that user object, if they're immediately eligible, that User's object for the Power in the Eligible model is created and the eligible field is set to true, if they're not eligible, it's set to false. Now, the thing is, I want to make them eligible on the eligibility date specified in the Power object. But how do I do that? Schedule a task for every object for a date? Run a task every 24 hours that iterates over all the un-eligible Users and make's them eligible if the date is of the eligibility date? If so, how do I do either of those? Thank you for your … -
How to put rate limit rules for each different user in django
I'm trying to put a rate limit for each different user when they are trying to access a view. Here is my code: class Profil(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) rate=models.IntegerField(default=0) models.py @login_required def flights(request): rate=str(Profil.objects.get(user=request.user).rate) is_ratelimited(request, key='get:user', rate=rate+'/m') .... But when I to a get on this view I get this error : 'NoneType' object has no attribute 'module' What am I doing wrong? Do you have better idea to do I want? -
More convenient way to get related object in Django
I need to render different templates for logged in user depending on its "type": I have a custom User called Users to store the general fields, and three different user types, called Admins, Publishers and Copywriters, linked to the Users table with One-To-One relation class Users(AbstractUser): # fields class Admins(models.Model): user = models.OneToOneField(Users, on_delete=models.CASCADE) # extra fields for admins... class Publishers(models.Model): user = models.OneToOneField(Users, on_delete=models.CASCADE) # extra fields for publishers... class Copywriters(models.Model): user = models.OneToOneField(Users, on_delete=models.CASCADE) # extra fields for copywriters... Which is the most convenient way tho retrieve the related fields of the logged user? Or in other words, how can i retrieve the admins or publishers or copywriters object related to the logged user? My original idea was to add a column in the Users table called user_type but it seems to me a redundant field since there's a One-To-One relation -
Django - How to tie data for verification that is stored in separate models?
I'm fairly new to python. I'm making a form that has a few fields from my model. The first field of this model, called EmployeeWorkAreaLog is Employee#/adp number, which is just a regular ID#. I have another model, called Salesman that is used as the main database with all the employees, and has each person's info, along with their employee #. What I was trying to achieve is that the form doesn't submit if the employee # is not valid, meaning is not currently in Salesman model. Below is what I tried to do, but I noticed that this is tying the Employee # to the auto-generated ID in the database, not the adp_number. I tried to make some changes with how the relation is but every time I ended up having to modify the Salesman model, which I cannot do, because it said something about the field being unique. Note that, in my EmployeeWorkAreaLog, the same employee can have multiple entries, so I don't know if that's what might be causing this. How could I approach this without changing Salesman? And, secondary question, not as crucial, is there any way that, upon submission, I can copy the slsmn_name from … -
Formfield displayed based on treatment group
I am programming an experiment with different treatment Groups. For Treatment Group 3 and 4, I want to know the name of the Participants by using a form field. For the Control Group and Treatment Group 1 - 2, the name is irrelevant and thus, there should not be a forms_field. I ws already thinking of excluding the form field in HTML by using if loops, so if treatment = 3 or 4, display the field. However, I cannot proceed to the next page for the other Treatment Groups since the field shouldn't be blank. Inserting a blank=True is not really an option since Treatment Group 3 and 4 could just skip the name. I want to "force" Treatment Group 3 and 4 to give me their name. My code is too long to post it here, so I'll just post the relevant passages: Modelsview class Subsession(BaseSubsession): def creating_session(self): treatmentgroup = itertools.cycle(['ControlGroup','one','two','three', 'four']) for p in self.get_players(): p.treatmentgroup = next(treatmentgroup) class Group(BaseGroup): pass class Player(BasePlayer): name = models.StringField(label="Your Name:") transcribed_text = models.LongStringField() levenshtein_distance = models.IntegerField() guthaben = models.CurrencyField(initial=c(0)) cumulative_guthaben = models.CurrencyField() Pagesview class Welcome(Page): form_model = 'player' def is_displayed(self): return self.round_number == 1 class Introduction(Page): form_model = 'player' def is_displayed(self): … -
save() missing 1 required positional argument: 'self' in django blog
I'm learning Django and work on a comment system. Model class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') comment_user = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return 'comment by {} on {}'.format(self.comment_user, self.post) Views def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': new_comment = CommentForm(request.POST) if CommentForm.is_valid: new_comment = CommentForm.save(commit=False) new_comment.post = post new_comment.comment_user = request.user new_comment.save() else: new_comment = CommentForm context = { 'post': post, 'comments':comments, 'new_comment': new_comment, 'CommentForm': CommentForm } return render(request, 'blog/post/detail.html', context) When I try to create a new comment this error occurs TypeError at /blog/2019/10/29/my-second-post/ save() missing 1 required positional argument: 'self' Request Method: POST Request URL: http://127.0.0.1:8000/blog/2019/10/29/my-second-post/ Django Version: 2.2.6 Exception Type: TypeError Exception Value: save() missing 1 required positional argument: 'self' Exception Location: E:\v_envs\elkhashen\src\blog\views.py in post_detail, line 35 Python Executable: E:\v_envs\elkhashen\Scripts\python.exe Python Version: 3.7.4 Python Path: ['E:\\v_envs\\elkhashen\\src', 'E:\\v_envs\\elkhashen\\Scripts\\python37.zip', 'E:\\v_envs\\elkhashen\\DLLs', 'E:\\v_envs\\elkhashen\\lib', 'E:\\v_envs\\elkhashen\\Scripts', 'c:\\users\\elkhashen\\appdata\\local\\programs\\python\\python37-32\\Lib', 'c:\\users\\elkhashen\\appdata\\local\\programs\\python\\python37-32\\DLLs', 'E:\\v_envs\\elkhashen', 'E:\\v_envs\\elkhashen\\lib\\site-packages'] Server time: Thu, 31 Oct 2019 09:50:45 +0000 -
Can't overwrite variable value in django signal
Why when I set active_template = home.template in django signal everything looks fine untill I "click" again "save" button in admin panel. Then active_template variable is set again to 0. Shoudn't be overwrite when I run signal again? I try this with normal function and it work so I guess the problem is signal. model: class Homepage(models.Model): choice_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} TEMPLATE_TYPE = [ (choice_dict['one'], '1'), (choice_dict['two'], '2'), (choice_dict['three'], '3'), (choice_dict['four'], '4'), (choice_dict['five'], '5'), ] template = models.IntegerField(choices=TEMPLATE_TYPE, null=True, blank=True) content = RichTextUploadingField(null=True, blank=True) signal def default_value(sender, instance, **kwargs): test = ['test','test1','test2'] home = Homepage.objects.first() active_template = 0 if home.template and active_template != home.template: Homepage.objects.filter(pk=2).update(content=test[home.template]) active_template = home.template post_save.connect(default_value, sender=Homepage) -
DatePicker not visible using a ModelForm - crispy
I have a modelForm base on my model Randomization I'm using crispy in my template (Randomzation_edit.html) and DateInput() in my form (RandomizationForm) unformtunatly, I did not have DatePicker in my edit form What is the problem? forms.py from django import forms from .models import Randomisation class RandomisationForm(forms.ModelForm): TYPES = [ (1, 'On-line'), (2, 'Telephon'), ] ran_num = forms.CharField(label="Patient code",disabled=True) ran_dat = forms.DateInput() ran_pro = forms.ChoiceField(label="Type", widget=forms.Select, choices=TYPES) class Meta: model = Randomisation fields = ('ran_num','ran_dat','ran_inv','ran_pro','ran_pro_per','ran_crf_inc','ran_tbc','ran_crf_eli','ran_cri','ran_sta','ran_vih','ran_bra','ran_med',) models.py class Randomisation(models.Model): ran_ide = models.AutoField(primary_key=True) ran_num = models.CharField("Patient code", max_length=10, unique=True, null=True, blank=True) ran_dat = models.DateTimeField("Today's date", null=True, blank=True) ran_inv = models.CharField("Investigator", max_length=20, null=True, blank=True) ran_pro = models.IntegerField("Procedure used to randomized", null=True, blank=True) ran_pro_per = models.IntegerField("if telephone, name of the person reached on the phone", null=True, blank=True) ran_crf_inc = models.IntegerField("Was the CRF inclusion 2 Eligibility fulfilled?", null=True, blank=True) ran_tbc = models.IntegerField("Is TB diagnosis possible, probable or definite?", null=True, blank=True) ran_crf_eli = models.IntegerField("Was the CRF Inclusion 2 Eligibility fulffiled?", null=True, blank=True) ran_cri = models.IntegerField("Is the conclusion All criteria fulfilled for randomisation", null=True, blank=True) ran_sta = models.IntegerField("British Medical Council Staging (worst stage reported between first symptoms and now)", null=True, blank=True) ran_vih = models.IntegerField("HIV/AIDS status", null=True, blank=True) ran_bra = models.IntegerField("TB treatment assigned", null=True, blank=True) ran_med = models.IntegerField("Batch … -
NestedRouter with Django Rest Framework
I am using Django Rest Framework and needed a nested router/url like /authors/<pk>/books/<pk> With one more requirement of possible custom actons like: /authors/custom_action /authors/<pk>/other_custom_action Drf-extensions seems to support nested routers nicely out of the box. But won't work if @detail_route is needed on a viewset action. It seems that ViewSet can only have standard methods, and @detail_routes won't work if I need an additional link on root viewset, e.g. /authors/bio (seating under detail_url). This brings to questions: is it still possible with drf-extensions to use detaul_route? if not, is creating an imitation of nested viewset right inside parent Viewset class, via a set of methods like @detail_route/nested_crud, an overkill, architecturally speaking? -
How to map one social account to several user account with django-allauth
I need to map one social account (created on a Django server with django-oauth-toolkit) to several different logins in a Django website. I already managed to connect and the server passes all allowed accounts so that the client connects as one of them. I'd like to add the possibility to prompt for the choice of which of the accounts should be used. I'm currently connecting the user in the pre_social_login method of the account adapter. The only idea I have is to persist in the session the available accounts and redirect to a page to select the preferred one. I'd like to understand if there's a better way. -
Django Python if block on template file (string)
I am trying to ad a condition into an html model in Django (python) and it is not working: This is my HTML: <p class="card-text text-muted h6">{{ post.author }} </p> {% if post.author == 'John_Woo' %} <p class="card-text text-muted h6"> NOK </p> {% else %} <p class="card-text text-muted h6"> ok </p> {% endif %} Not sure what is wrong here... Even though I have a John_Woo author, I only get ok message -
How can I set the best configurations for the project working with django, docker and mysql?
I was reading an article in here which is about setting up project using docker, django and mysql together. these are my files in project: Dockerfile FROM python:3.7 MAINTAINER masoud masoumi moghadam ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app ADD . /app ADD requirements.txt /app/requirements.txt RUN pip install --upgrade pip && pip install -r requirements.txt Docker-compose version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=localhost - DB_NAME=contact_list - DB_USER=root - DB_PASS=secretpassword depends_on: - db db: image: mysql:5.7 environment: - MYSQL_DATABASE=contact_list - MYSQL_USER=root - MYSQL_PASSWORD=secretpassword requirements Django>=2.0,<3.0 djangorestframework<3.10.0 mysqlclient==1.3.13 django-mysql==2.2.0 and also this settings in my setting.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': os.environ.get('DB_HOST'), 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS') } } When I use docker-compose build I face no problem and everything is just fine. Then I run service mysql start. I can assure that mysql service is in run and works because I have access to datasets. The problem occurs when I do the migration using this command docker-compose run app sh -c "python manage.py makemigrations core" I get this error: django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket …