Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple Foreign Keys entry in Django Admin
I am having an issue with a projectapp in Django. Basically, what I need to do is creating a page where I display the item contained in a certain flight mission (I am developing the software for a flight school). The models code should be something like this: models.py class FlightMissionItem(models.Model): flight_item = models.CharField(max_length=800) class FlightMission(models.Model): title = models.CharField(max_length=300) pre_flight_comment = models.TextField(blank=True, null=True) flight_item = models.ForeignKey( FlightMissionItem, on_delete=models.CASCADE) grading = models.CharField( max_length=1, choices=GRADING_CHOICES, null=True, blank=True) flight_comment = models.TextField(blank=True, null=True) debriefing_comment = models.TextField(blank=True, null=True) What I am trying to do, is to have multiple flight_item inside the FlightMission model. I post also the admin models: admin.py class FlightMissionItemAdmin(admin.StackedInline): model = FlightMission class FlightMissionAdmin(admin.ModelAdmin): inlines = [FlightMissionItemAdmin] The problem is that, anytime I try to modify the admin.py, I receive an error like this: <class 'flight.admin.FlightMissionItemAdmin'>: (admin.E202) 'flight.FlightMission' has no ForeignKey to 'flight.FlightMission'. The only way I was able to find a loophole in the error was to add another ForeignKey to the FlightMissionItem model. The problem was that basically I was able to loop over just 1 item in the FlightMission later on, so I wasn't able to display anything useful in the HTML. I hope that is clear, otherwise I'll … -
Get prefix from Netherlands names
I have a social network with users from the Netherlands on Django. With my site I can get the Netherlands name, for example, Jap van der Stael, and I need to get only van der part. For this name it's not a problem, but how to get infix from a name like Jap van der Vulpen - Odijk? For now i have next code: ' '.join(last_name.split()[:-1] But if last name is Jap van der Vulpen - Odijk, its return 'van der Vulpen -' -
How to show the profile of the post author from post detail Django
I want to show the author profile to the visitors, who visit the post details. My views.py is: def usercv(request): post = Post.objects.filter(id=id) postusercv = post.author.profile context={ 'posts':postusercv } return render(request,'arcmap/usercv.html',context) My urls.py is: path('post/usercv/',views.usercv,name='user-cv'), my user_cv.html is: {% extends 'arcmap/base.html'%} {% block content%} {% for post in posts %} {{post.username}} {% endfor %} {% endblock %} Inside of the post_detail, I use the link which is: <h4> Our Profile:</h4><a href="{% url 'user-cv'%}">Our profile</a> And the error is: TypeError at /post/usercv/ Field 'id' expected a number but got <built-in function id>. -
remove an element from select once added to the db (filtering)
post code and photos because I don't know how to explain the problem. I have this green button that opens a modal which allows me to create a group and save it in the db once clicked on add group. After adding the object in the db I reload the page with the data entered via modal, if I click again on the green button I have the possibility to add another object. The problem that I can always add the same object in the select, I wish that once added there is no longer the possibility to add it. form class EserciziForm(forms.ModelForm): class Meta: model = models.DatiEsercizi exclude = ['gruppo_single'] class GruppiForm(forms.ModelForm): class Meta: model = models.DatiGruppi exclude = ['gruppi_scheda'] html {% extends "base.html" %} {% load widget_tweaks %} {% block content %} <section class="container mt-3"> <div class="d-flex align-items-center justify-content-between"> <h1 class="nome-scheda">CREA</h1> <a href="{% url 'lista-gruppi' %}" class="btn btn-outline-primary">LISTA</a> </div> <hr> <div class="scheda mb-4"> <div class="d-flex justify-content-between align-items-center"> <h4 style="margin-bottom: 0;">Nome: {{ scheda.nome_scheda }}</h4> <div> <p style="margin-bottom: 0;"> <span><strong>Inizio: {{ scheda.data_inizio }}</strong></span> | <span><strong>Fine: {{ scheda.data_fine }}</strong></span> </p> </div> </div> </div> <div class="box"> {% for gruppo in scheda.gruppi_scheda.all %} <div class="gruppo mb-3"> <div class="d-flex justify-content-between align-items-center"> <p style="margin-bottom: 0;">{{ … -
(Django) Delete function does not remove data from database
Currently I'm having a table that shows the list of drugs. This table has a delete button in every data row. When I click it, the row does not go away. I tried the same delete syntax (in the function called 'destroy') in Django shell and it worked. I just don't understand why when I clicked on the Remove button inside the template, nothing happened, even after refreshing. drugs/views.py from django.shortcuts import render, redirect from django.views.generic import ListView from .models import ( Drug, ) from .forms import ( DrugForm, ) def add_drug(request): forms = DrugForm() if request.method == 'POST': forms = DrugForm(request.POST) if forms.is_valid(): drug_id = forms.cleaned_data['drug_id'] name = forms.cleaned_data['name'] drug_type = forms.cleaned_data['drug_type'] Drug.objects.create(drug_id=drug_id, name=name, drug_type=drug_type) return redirect('drug-list') context = { 'form': forms } return render(request, 'drugs/add_drug.html', context) def destroy(request, drug_id): d = Drug.objects.get(drug_id=drug_id) d.delete() d.save() return redirect("/") class DrugListView(ListView): model = Drug template_name = 'drugs/drug_list.html' context_object_name = 'drug' ddms/urls.py from django.contrib import admin from django.urls import path, include # local from .views import base, dashboard from drugs.views import destroy urlpatterns = [ path('admin/', admin.site.urls), path('', dashboard, name='dashboard'), path('drugs/', include('drugs.urls')), path('delete/<int:drug_id>', destroy), ] templates/drugs/drug_list.html <div class="card-body--"> <div class="table-stats order-table ov-h"> <table id="bootstrapdatatable" class="table"> <thead> <tr> {% comment %} <th class="serial">#</th> … -
Django multiple user roles in many organisations
I am trying to design a multiple user model where a user can have different roles for different organisations, for example; User A can be an admin for organisation_1 User A can be an employee for organisation_2 User A can be a manager for organisation_3 User B is an employee for organisation_1 What I have found is to use the abstract user; class User(AbstractUser): is_user = models.BooleanField('student status', default=False) is_admin = models.BooleanField('student status', default=False) is_manager = models.BooleanField('student status', default=False) is_employee = models.BooleanField('teacher status', default=False) The way I see it is that it can work if you have one or many roles but under one organisation. How can I connect this to an organisation model? -
App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz at deploying project on heroku server
Django project deploy on heroku server, at the time fetch an error at push a project on heroku. Enumerating objects: 63, done. Counting objects: 100% (63/63), done. Delta compression using up to 4 threads Compressing objects: 100% (60/60), done. Writing objects: 100% (63/63), 335.77 KiB | 11.19 MiB/s, done. Total 63 (delta 3), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to youtube-to-mp3converter. remote: To https://git.heroku.com/youtube-to-mp3converter.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/youtube-to-mp3converter.git' How can solve it. -
Update django without pip [duplicate]
I have to install django, but when I installed it, it was one of the oldest version (1.10). I would like to update the package but without pip because I do not have internet connection in this computer. Anyone have a solution ? -
How to convert a django model field to different dimension on save?
I'd like to convert dollars to cents on save for the Django model. How can I do it by using the Django Model environment? -
Django static style.css styling
I want to share this problem that I got, I made 2 apps in my Django project and one of the apps has a static folder with the file style.css. Everything works but when I try to add a new style let's say I am adding some styling to a div it does not work apparently. Only some of the styles work(older styles) then new ones I try to add it just does not work in templates. -
Mock a const in python
I have in view filterset_class = main_app.api.filters.TestClassFilter and there field id__in class TestClassFilter(FilterSet): id__in = BaseInLimitFilter( field_name="id", label='Id in', limit=LIMIT ) with custom filter class api.filters.BaseInLimitFilter class BaseInLimitFilter(BaseInFilter): message = _("At most {} values are allowed.") limit = 10 def __init__(self, *args, **kwargs): if 'limit' in kwargs: self.limit = kwargs.pop('limit') super(BaseInLimitFilter, self).__init__(*args, **kwargs) def filter(self, qs, value): if len(value) >= self.limit: raise ValidationError({ "id__in": self.message.format(self.limit) }) return super(BaseInLimitFilter, self).filter(qs, value) I try mock const api.const.LIMIT and set value as 1 in my test but I have problem with it. I tried something like that: @mock.patch('main_app.api.filters.LIMIT', 1) Does anyone have any ideas what am I doing wrong? -
Django Form validation error (Select a valid choice) when use "queryset=Product.objects.none()"
I use formset_factory when I get an order for products product_formset = formset_factory(OrderProductsForm,extra=5) It works when I use “qeryset=Product.objects.all()” in “OrderProductsForm(forms.ModelForm):“ self.fields['product'] = ModelChoiceField(queryset=Product.objects.all(),empty_label="Ürün Seciniz", widget=forms.Select(attrs={"onChange":'stokKontrol(this.value,this.id)'})) but it gets all products so page load time increase. I would like to use “queryset=Product.objects.none() “ But at that point when I check the form in my view.py if request.method == "POST": formset = product_formset(request.POST) if formset.is_valid(): get an error as “Select a valid choice. That choice is not one of the available choices.” Do you have any suggestion ? thanks Forms.py class OrderProductsForm(forms.ModelForm): class Meta: model = OrderProducts fields = ['amount'] def __init__(self, *args, **kwargs): super(OrderProductsForm, self).__init__(*args, **kwargs) self.fields['product_category'] = ModelChoiceField(queryset=ProductCategory.objects.all(),empty_label="Ürün Grubunu seciniz", widget=forms.Select(attrs={"onChange":'myFunction(this.value,this.id)'})) #self.fields['product'] = ModelChoiceField(queryset=Product.objects.all(),empty_label="Ürün Seciniz", widget=forms.Select(attrs={"onChange":'stokKontrol(this.value,this.id)'})) self.fields['product'] = ModelChoiceField(queryset=Product.objects.none() ,empty_label="Ürün Seciniz",required=False,widget=forms.Select(attrs={"onChange":'stokKontrol(this.value,this.id)'})) self.fields['stok'] = forms.CharField(required=False,disabled=True,max_length=5) -
Django: Cannot update foreign key values in a model
When I create this model, the values are nulls. class TestRequest(models.Model): class Meta: verbose_name_plural = "TestRequest" title = models.CharField(max_length=256, null=True, blank=True) testConfiguration = models.ForeignKey( TestConfiguration, on_delete=models.PROTECT, null=True, blank=True) testDescription = models.ForeignKey( TestDescription, on_delete=models.PROTECT, null=True, blank=True) The serializer: class TestRequestSerializer(serializers.ModelSerializer): class Meta: model = TestRequest fields = [ 'id', 'title', 'testConfiguration', 'testDescription', ] depth = 2 The view: @api_view(['PUT']) def TestRequestUpdate(request, pk): testRequest = TestRequest.objects.get(id=pk) serializer = TestRequestSerializer(instance=testRequest, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And when I want to update them later from the front-end with this state: id: 98 title: "title" testConfiguration: 31 testDescription: 32 I get this response: { "id": 98, "title": "title", "testConfiguration": null, "testDescription": null } Why can't I update it? -
Django ElasticSearch DSL partial matching using nGram analyzer
I'm quite new to the ElasticSearch topic and I'm trying to implement simple e-commerce search in my Django application using ElasticSearch with library django-elasticsearch-dsl Github repo . The thing I'm trying (extremely simplified) to achieve is that, considering these Django model instances: Red T-shirts Blue T-Shirts Nice T-Shirts for search term T-Sh I'll obtain all these three results: Red T-shirts Blue T-Shirts Nice T-Shirts So I have this model in shop/models.py (again very simplified) class Category(models.Model): title = models.CharField(max_length=150, blank=False) description = models.CharField(max_length=150, blank=False) # In reality here I have more fields def __str__(self): return self.title With shop/documents.py from elasticsearch_dsl import analyzer, tokenizer autocomplete_analyzer = analyzer('autocomplete_analyzer', tokenizer=tokenizer('trigram', 'nGram', min_gram=1, max_gram=20), filter=['lowercase'] )from elasticsearch_dsl import analyzer, tokenizer @registry.register_document class CategoryDocument(Document): title: fields.TextField(analyzer=autocomplete_analyzer, search_analyzer='standard') # Here I'm trying to use the analyzer specified above class Index: name = 'categories' settings = { 'number_of_shards': 1, 'number_of_replicas': 0, 'max_ngram_diff': 20 # This seems to be important due to the constraint for max_ngram_diff beeing 1 } class Django: model = Category fields = [ 'title', # In reality here I have more fields ] And finally, my shop/views.py class CategoryElasticSearch(ListView): def get(self, request, lang): search_term = request.GET.get('search_term', '') q = Q( "multi_match", query=search_term, fields=[ 'title', … -
Login to Django Admin page with UUID username
I have created a DRF api with a Account model identified by an UUID. I also use this UUID as the username and thus have to log in to the admin page by providing the UUID and password. However if I try this I get the error “6c3fe924-1848-483a-8685-c5b095f1” is not a valid UUID. Which is very strange since this is created using UUID.uuid4. My Account model is as follows class Account(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'id' objects = AccountManager() def __str__(self): return str(self.id) The AccountManager() referenced is a custom manager since this Account model is coupled with different types of user models. I do not think this code makes a difference but if anyone want me to upload this as well, let me know. -
Flask Form Submission POST Request repeating
I created an Contact Form which uses Flask at its Backend, after submission of the form a POST request will be send to the server @app.route("/contact", methods=["GET", "POST"]) def contact(): if request.method == "POST": firstname = request.form["firstName"] email = request.form["email"] phone = request.form["phone"] message = request.form["body"] return render_template("contact.html", msg_sent=True) elif request.method == "GET": return render_template("contact.html", msg_send=False) As seen in the above code after the submission the page redirects to the same page i.e contact.html msg_send will be True which changes the h1 tag in contact.html to Successfully sent... {% if msg_sent == True: %} <h1>Successfully Sent...</h1> {% else: %} <h1>Contact Me</h1> {% endif %} But I noticed when refreshed, the page makes the same post request again how can fix this ? I understood that the page is still having post request in its header but how can i change it to a GET after a refresh i.e to the Orginal Contact Form -
In Django's ORM, is there a way to detect whether code is executing inside a transaction?
Eg, I want this function: from django.db import transaction with transaction.atomic(): assert inside_transaction() == True assert inside_transaction() == False Is there a way to achieve this? Or is it possible to detect directly in psycopg2 if not in Django's ORM? -
Settings in Django run repeat when runserver
I don't know why my django app run settings/base.py 2 times. I think it would make my app slow down In my settings/base.py I printed print('this is base_dir') print(BASE_DIR) output is: this is base_dir F:\7.Django\BLOG_PROJECT\src_blog this is base_dir F:\7.Django\BLOG_PROJECT\src_blog This is my settings file: ├── settings <br /> | ├──__init__.py <br /> | ├──base.py <br /> | ├──dev.py <br /> | ├──prod.py <br /> and my settings\__init__.py file contain: import os from dotenv import load_dotenv load_dotenv() if os.environ['ENV_SETTING'] =='prod': from .prod import * else: from .dev import * from .base import * -
Form with ModelChoiceField(required=True) doesn't raise ValidationError if no option is selected
I have a form that raises ValidationErrors for all fields if they are not valid. However, if there is no option from the ModelChoiceField selected, the form both doesn't submit (which is fine) and doesn't raise any ValidationError in the template either. # Form class PollersForm(forms.Form): # Poller Category poller_category = forms.ModelChoiceField(widget=forms.RadioSelect(attrs={ 'class': 'poller-category-radio', }), queryset=Category.objects.all().order_by('category'), label='Select a Category', required=True) [..| # View def raise_poller(request): # check whether it's valid: if form.is_valid(): # process the remaining data in form.cleaned_data as required poller_text = form.cleaned_data['poller_text'] poller_category = form.cleaned_data['poller_category'] # passes all the time even if no choice is selected # Template <form action="/raisepoller/" method="post"> {% csrf_token %} {{ form.non_field_errors }} {{ form.errors }} [..] <!-- Poller Categories --> <div class="fieldWrapper"> <div class="label">{{ form.poller_category.label_tag }}</div> <div class="category-ctn"> {% for category in form.poller_category %} <div class="category-wrapper">{{ category }}</div> {% endfor %} </div> </div> <!-- Submit Button --> <button type="submit" value="Publish Poller" id="raise-poller-button"> <div class="button-wrapper"> <div class="button-icon"><img id="button-image" src="{% static 'images/send.png' %}"></div> <div class="button-text">Publish Poller</div> </div> </button> </form> -
Django values on m2m field doesn't return the same as same query on base Model
I expect a behaviour I'm not obtaining. Consider this example model: class Node(models.Model): name = models.CharField(max_length=30) # Verbose for readability class SpecialNode(Node): other_attr = models.CharField(max_length=30) class Edge(models.Model): nodes = models.ManyToManyField(Node, related_name="edges") I have a given node (that is not Special), and I want to know which Edges doesn't (or does) connect with a SpecialNode. If I do this, works: # All the edges except those which have a node that is a SpecialNode Edge.objects.filter(node__id=1).exclude(nodes__specialnode__isnull=False) Tho... this doesn't work, returns all the edges of the node instead. Node.objects.get(id=1).edges.exclude(nodes__specialnode__isnull=False) I don't know what I'm missing or missunderstanding, but I expect a queryset of edges with both sentences. -
Djnago custom permissions filtered by user role and id
I am working with Django Permissions and am trying to understand how to implement I have an extended User model, where users have roles: class UserCustomModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) ROLES = ( ('ADMIN', 'ADMIN'), ('SUPERUSER', 'SUPERUSER'), ('CONTRIBUTOR', 'CONTRIBUTOR'), ('READER', 'READER'), ) roles = models.CharField(max_length=50, choices=ROLES, null=True) deleted = models.IntegerField(default=1) last_change_date = models.DateTimeField(auto_now=True) And there is a model for clients (firms): class CustomClient(models.Model): client_id = models.AutoField(primary_key=True) client_name = models.TextField() client_description = models.TextField() deleted = models.IntegerField(default=1) last_change_date = models.DateTimeField(auto_now=True) def __str__(self): return str(self.client_name) Each user can be assigned to exactly one client. It is displayed in the third model: class ClientUser(models.Model): class Meta: unique_together = (('user', 'client', 'group'),) user = models.ForeignKey(User, on_delete=models.CASCADE, primary_key=True) client = models.ForeignKey(CustomClient, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) deleted = models.IntegerField(default=1) last_change_date = models.DateTimeField(auto_now=True) And I created groups in Django for each role: Admins Superusers Contributors Readers The idea is to assign user to a group by his/her role. It works fine, but I want to set custom permissions on these groups. Like for example if a user has role SUPERUSER then he/she can add/change/delete users with roles CONTRIBUTOR and READER. Or if a user is ADMIN he/she can add/change/delete users with all other roles. And it … -
URL parameter repeated in Django
this is my URL here number again repeated page work properly but number repeated. <a href="/hotfix/all/?page={{ i }}&number={{number_data}}/> /hotfix/all/?page=3&number=10&number=10 -
select filtering by removing elements already present in the db
I'm trying to filter my group table in the sense that if there is already a group created the select (see photo) must not show me that group already created in the db -
Cannot assign multiple instances
I need to override my create method. I want to create multiple skills for one candidate in one request. I am getting the error that cannnot assign multiple instances class CandidateSkill(models.Model): candidate = models.ForeignKey(Candidate,on_delete=models.CASCADE,related_name="skills",) skills = models.ForeignKey("jobs.Skill",on_delete=models.CASCADE,related_name="candidate_skills", ) ---------- class CandidateSkillList(generics.ListCreateAPIView): serializer_class = CandidateSkillSerializer queryset = CandidateSkill.objects.all() class SkillSerializer(serializers.ModelSerializer): class Meta: model = Skill fields = ("name",) ---------- class CandidateSkillSerializer(serializers.ModelSerializer): skills = SkillSerializer(many=True) class Meta: model = CandidateSkill fields = ["id", "candidate", "skills"] def create(self, validated_data): skills = validated_data.pop("skills") candidateskills = CandidateSkill.objects.create(**validated_data) for skill in skills: Skill.objects.create(candidate_skills=candidateskills, **skill) return candidateskills -
Permission Error: trying to execute passenger_wsgi.py for a django app on centos 7
this is the passenger_wsgi.py file: import sys, os ApplicationDirectory = 'djangoProject' ApplicationName = 'djangoProject' VirtualEnvDirectory = 'python-app-venv' VirtualEnv = os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin', 'python') if sys.executable != VirtualEnv: os.execl(VirtualEnv, VirtualEnv, *sys.argv) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory)) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory, ApplicationName)) sys.path.insert(0, os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin')) os.chdir(os.path.join(os.getcwd(), ApplicationDirectory)) os.environ.setdefault('DJANGO_SETTINGS_MODULE', ApplicationName + '.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() This the error i'm getting (nginx logs in /var/nginx/error.log): Traceback (most recent call last): File "/usr/share/passenger/helper-scripts/wsgi-loader.py", line 369, in <module> app_module = load_app() File "/usr/share/passenger/helper-scripts/wsgi-loader.py", line 76, in load_app return imp.load_source('passenger_wsgi', startup_file) File "/var/www/vhosts/lots.credit-wiin.com/httpdocs/passenger_wsgi.py", line 7, in <module> if sys.executable != VirtualEnv: os.execl(VirtualEnv, VirtualEnv, *sys.argv) File "/usr/lib64/python2.7/os.py", line 312, in execl execv(file, args) OSError [Errno 13] Permission denied The file works fine if I execute it from terminal (python passenger_wsgi.py) The VirtualEnv file have 777 permissions Any help ?