Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Save extra fields to django model apart from the fields which were present in django forms using the form.save method
I have a Django model with few fields, In the django forms which is created using that django models. While using the forms.save method I also want to save the extra fields which were not present in Django forms but present in django models. models.py class NewProvisionalEmployeeMail(models.Model): STATUS_CHOICES = ( (1, ("Permanent")), (2, ("Temporary")), (3, ("Contractor")), (4, ("Intern")) ) PAY_CHOICES = ( (1, ("Fixed")), (2, ("Performance Based")), (3, ("Not Assigned")), ) POSITION_CHOICES = () for i, name in enumerate(Position.objects.values_list('position_name')): POSITION_CHOICES += ((i, name[0]),) email = models.EmailField(max_length=70, null=False, blank=False, unique=False) token = models.TextField(blank=False, null=False) offer_sent_by = models.CharField(max_length=50) position_name = models.IntegerField(choices=POSITION_CHOICES, null=True, blank=True) accepted = models.BooleanField(default=False) name=models.CharField(max_length=30) user_name=models.CharField(max_length=30) pay = models.IntegerField(default=0) title = models.CharField(max_length=25, null=True, blank=True) pay_type = models.IntegerField(choices=PAY_CHOICES, default=3) emp_type = models.IntegerField(choices=STATUS_CHOICES, default=1) def __str__(self): return str(self.offer_sent_by) +" to " + str(self.email) def clean(self): if(NewProvisionalEmployeeMail.objects.filter(email=str(self.email)).exists()): NewProvisionalEmployeeMail.objects.filter(email=str(self.email)).delete() def save(self, **kwargs): self.clean() return super(NewProvisionalEmployeeMail, self).save(**kwargs) If you see it has following fields : email, token, offer_sent_by, position_name, accepted, name, user_name, pay, title, pay_type, emp_type. Now I only want the following fields in my forms : email, position_name, name, user_name, pay, title, pay_type, emp_type and not token and offer_sent_by whose values will be determined in my views.py using some logic. forms.py class NewProvisionalEmployeeMailForm(ModelForm): class … -
Django Rest Framework: How to include application namespace when defining HyperlinkedRelatedField
My django application has a namespace defined in the app_name variable, in urls.py. It seems like this namespace needs to be specified in the view_name argument of HyperlinkedRelatedField for HyperlinkedRelatedField to successfuly retrieve the relevant url router. To avoid repeating this namespace, I'd like to import the namespace into the serializers module. However I get an import error when doing so. extract from my app/urls.py: ... app_name = 'viewer' ... api_router = DefaultRouter() api_router.register('year', api_views.YearViewSet, 'api_year') api_router.register('month', api_views.MonthViewSet, 'api_month') ... urlpatterns = [ ... path('api/', include(api_router.urls)), ] api_views.py ... class YearViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet): queryset = Year.objects.all().order_by('-date') serializer_class = YearSummarySerializer lookup_field = 'slug' def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = YearDetailSerializer(instance=instance) return Response(serializer.data) @action(detail=True) def months(self, request, *args, **kwargs): serializer = YearMonthsSerializer(instance=self.get_object(), context={'request': request}) return Response(serializer.data) ... serializers.py ... from .urls import app_name ... class YearMonthsSerializer(serializers.HyperlinkedModelSerializer): month_set = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name= app_name + ':api_month-detail', lookup_field='slug' ) class Meta: model = Year fields = ['month_set'] ... When I manually enter the app_name ('viewer') the serializer works as intended, however when I try to import app_name from .urls, python throws an ImportError ImportError: cannot import name 'app_name' from 'cbg_weather_viewer.viewer.urls' I don't understand why I get this import error as … -
How would you incorporate Java into a Python Application to make an API request?
I'm building a python web app using the Django framework, but I've hit a problem. The Amazon API I want to use uses Java and doesn't support Python. How would I do this? I'm thinking of creating and API to send JSON data from my Python app to another API written in Java to make the request from the Amazon API and then send it back like that. New to all this so I don't know if that would work? Seems logical to me? How would you go about this, at the moment I've never touched Java. -
How to set gis_enable to True
I have a geoDjango setup with postgresql/postgis and everything works fine. Now I try to install django-raster but it fails on migration. The error is Raster fields require backends with raster support. It happens because connection.features.gis_enabled is set to False in site-packages/django/contrib/gis/db/models/fields.py How to set it to True ? -
Time Spent by User on a Particular WebPage/Form - Django
I want to track the time spent by a user on a particular Django webpage and upload it to the admin. Can this be done with the Python time module? If so how can I do it? I am also open to other suggestions, but since I am a beginner I would prefer them to be simple. Thanks in advance. -
How to query complicated query with json_field
In my django app I have the following model hirarchy: Project BuildingCollection (belongs to Project) Building (belongs to BuildingCollection) SpecificValue (belongs to Building) The SpecificValue model has a JSON Field with lots of keys and values, like {1:value2, 2: value2, 3:value3.....}. The SpecificValue model also has a choice field which has 3 choices of types. I am trying to query the following through the URL which looks like so: path('blbla/<str:project>/<str:type>/<str:key>/', blbla.as_view()) In pseudocode I want to query this: Give me all buildings of the most recent BuildingCollection of the project passed in my URL. Then give me all the SpecificValues of these buildings, but only those which type was passed in the URL. And finally give me from all these SpecificValues just the values to the specified key within the JSON field. Then I want to write it into a dictionary saying: {"Building1" : valueofJSONField, "Building2" : valueofJSONField } I hope I am clear in what I am saying. I am trying this with the following (overwriting the get method of REST APIView) class MyClass(APIView): def get(self, request, **kwargs): project = kwargs.get('project') type = kwargs.get('type') key = kwargs.get('key') building_group_most_recent = BuildingCollection.objects.filter( project__project_name=project).order_by('-creation_date').first() #I get mostrecent buildings = building_collection_most_recent.buildings.all() ##all buildings … -
how to create 2 admin users in django where each user will administer only the users he creates?
I need to create more than 1 admin user who can administer roles/permissions to only the users he creates in django.This admin should be able to see only the users he creates and not the users created by another user. In short I wish to use the django as a SaaS model for my customers, where he can administer his employees/users only.Is this possible and how exactly can this be implemented? -
The current path, account/ active/muSxcXQedffNqDxt/, didn't match any of these
error picture Why it didn't match the url 7? urls.py: path('active/(?P<active_code>.*)/$', ActiveUserView.as_view(), name='active_user'), views.py: class ActiveUserView(View): def get(self,request,active_code): users = UserProfile.objects.filter(code=active_code) if users: users.is_active = True users.save() else: users.delete() return HttpResponse('Fail!Register Again!') return HttpResponseRedirect(reverse("account:user_login")) -
How do I redirect admin login to a custom view and redirect them back to the admin dashboard after they have finished with my custom view
The custom view is going to be my own version of 2 factor authentication (I Know django-otp exists but I am doing this to challenge myself and learn). I am unaware of how to change the admin login redirection and where I should redirect using HttpResponseRedirect so that they go to the admin dashboard after they are done. As always, I am greatful for all your suggestions! Note: I am using django 2.2 with python 3.6