Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 ? -
send a variable to multiple pages with return render django
I want to send a variable when the user is connected (connect = true ) on the connect method, to change the navbar , what im trying to do is send the variable to all the pages on my project, this way i can check with a condition. Is there a way to do it with return render , I checked on the internet , but find nothin helpfull. -
django rest Error - AttributeError: module 'collections' has no attribute 'MutableMapping'
I'm build Django app, and it's work fine on my machine, but when I run inside docker container it's rest framework keep crashing, but when I comment any connection with rest framework it's work fine. My machine: Kali Linux 2021.3 docker machine: Raspberry Pi 4 4gb docker container image: python:rc-alpine3.14 python version on my machine: Python 3.9.7 python version on container: Python 3.10.0rc2 error output: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/test.py", line 55, in handle failures = test_runner.run_tests(test_labels) File "/usr/local/lib/python3.10/site-packages/django/test/runner.py", line 728, in run_tests self.run_checks(databases) File "/usr/local/lib/python3.10/site-packages/django/test/runner.py", line 665, in run_checks call_command('check', verbosity=self.verbosity, databases=databases) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 181, in call_command return command.execute(*args, **defaults) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/check.py", line 63, in handle self.check( File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/usr/local/lib/python3.10/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/usr/local/lib/python3.10/site-packages/django/core/checks/urls.py", line 13, in check_url_config return … -
Django: organizing models in a package after migration
I have a models.py file with models in it. Now I want to reorganize these models into a package as described in an official documentation. Can I do it with the existing models? How does it affect previous migrations? -
Should I put my user profile models in the same app that handles account signup and login
In my django project I have an app called "accounts" that handles sign up and logins. Upon authentication, It redirects to 3 other apps depending on the type of user. The profiles of each user type is different and I don't know where to put the user profile models. Should I put them in the "accounts" app or in the other 3 apps? I currently have them inn their individual apps but I want to know what the better way to do it is. -
How i can access user which is logged in now to receiver function [duplicate]
so i want to create object from last_action on save of each models(Cars,Books,Carrots), but as far as i know instance is only passing attributes of sender model. So now i want to as well use user which is logged in, but i do not know how to pass it to my object, because sender model does not have it. How can i access to user and pass it to my object? signals.py @receiver(post_save,sender=Cars) @receiver(post_save,sender=Books) @receiver(post_save,sender=Carrots) def Save_last_editor(sender,instance,**kwargs): last_action.objects.create(item=instance.item,user = ???) models/items.py class Items(models.Model): name = models.CharField(max_length=30, unique=True) models/carrots.py class Cars(models.Model): name = models.CharField(max_length=30, unique=True) item = models.ForeignKey('Item', on_delete=models.PROTECT) models/carrots.py class Books(models.Model): name = models.CharField(max_length=30, unique=True) item = models.ForeignKey('Item', on_delete=models.PROTECT) models/last_action.py class LastAction(models.Model): item = models.ForeignKey('Item', on_delete=models.PROTECT) user = models.ForeignKey('User', on_delete=models.PROTECT) last_update = models.DateField(auto_now_add=True) -
How to enable page refreshing favicon in browser tab?
Do you know any methods, statements, events to trigger the page reloading favicon? I got <!DOCTYPE html> <html lang="en"> <head> <link rel="icon" type="image/png" href="myfavicon.ico" /> ... </head> <body> ... </body> </html> Of course i can press F5 to reload the page, but it is undesirable, like as using <form> </form> tags or <input> </input> etc. How to trigger loading favicon, without page reloading? -
How to integrate google calendar in my website?
I am trying to access and show the google calendar of any user (after login) in my website using django. User can change the calendar from the website and it should be visible in google calendar. I dont want to make user calendar public. (Ref) This is what I did. def connect_google_api(): creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json') if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file('credentials2.json',SCOPES) creds = flow.run_local_server(port=0) with open('token.json','w') as token: token.write(creds.to_json()) service = build('calendar','v3',credentials=creds) now = datetime.datetime.utcnow().isoformat()+'Z' page_token = None calendar_ids = [] while True: calendar_list = service.calendarList().list(pageToken=page_token).execute() for calendar_list_entry in calendar_list['items']: print(calendar_list_entry['id']) if "myorganization" in calendar_list_entry['id']: # print(calendar_list_entry['id']) calendar_ids.append(calendar_list_entry['id']) page_token = calendar_list.get('nextPageToken') if not page_token: break print(calendar_ids) for calendar_id in calendar_ids: count = 0 print(calendar_id) eventsResult = service.events().list( calendarId = calendar_id, timeMin = now, maxResults = 5, singleEvents = True, orderBy = 'startTime').execute() events = eventsResult.get('items',[]) # return calendar_ids,events response = JsonResponse(events,safe=False) # print(eventsResult) if not events: print('No upcoming events found') # print(events) print("-----------------------------------") I am able to get all the events of user's calendar. Now I want to show this calendar to the user. I trying to show these events using FullCalendar. document.addEventListener('DOMContentLoaded', function … -
How to troubleshoot a droplet on digital ocean that has a docker-django container running in it
I deployed my django docker via GitHub actions to Digital Ocean by following this tutorial and here is the code that was deployed. How can I see the logs of the droplet since I am not able to see my Django live on the link. I navigated to the digital ocean and I am able to open the console, but I am not sure how can I diagnose the issue from here.