Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
application error deploy using flask, heroku
successfully deployment app After successfully app deploy and when I click view then getting this error and in logs file not understand what is the problem. please help me out. enter image description here logs -
How To Fix create() takes 1 positional argument but 5 were given In python django
I'm Creating Login & Register Form In Django. I got an error create() takes 1 positional argument but 5 were given. code: def register(request): if request.method=="POST": username=request.POST['username'] name=request.POST['name'] email=request.POST['email'] password=request.POST['password'] user_create = User.objects.create(username,name,email,password) user_create.save() messages.success(request, " Your account has been successfully created") return redirect("/") else: return HttpResponse("404 - Not found") html https://paste.pythondiscord.com/amoturoqop.xml -
Django: STATIC_ROOT STATIC_ROOT can't join with BASE_DIR path
I set up my STATIC_ROOT like this STATIC_ROOT = os.path.join(BASE_DIR,'/vol/web/staticfiles') print('this is base_dir') print(BASE_DIR) print("this is static_root") print(STATIC_ROOT) When I run python manage.py runserver it print out this: this is base_dir F:\7.Django\BLOG_PROJECT\src_blog this is static_root F:/vol/web/staticfiles this is base_dir F:\7.Django\BLOG_PROJECT\src_blog this is static_root F:/vol/web/staticfiles When I run python manage.py collectstatic. Sure! It set my STATIC_ROOT AT F:/vol/web/staticfiles. I noticed that it print out the separate folder symbol different '/' and ''. I use windows os btw. Also don't know why it seems my app run settings 2 times. This is my settings ├── 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() # you need to set "ENV_SETTING = 'prod'" as an environment variable # in your OS (on which your website is hosted) if os.environ['ENV_SETTING'] =='prod': from .prod import * else: from .dev import * from .base import * -
Exception for 'NOT LIKE' in Oracle_SQL
in a database are many tables with the name 'D_...'. In a search query, all tables with 'D_%' should be ignored, except one. How do I handle this exception? many thanks Exception for 'NOT LIKE' in Oracle_SQL -
Sort django queryset using string field alphabetically
I want to sort users from model with their last names. I am using User.objects.filter(is_active=True).order_by('last_name') Still there is no luck. Pls suggest some solution. -
sender and instance arguments of post_save signal in Django
I'm confused with Django's post-save signal documentation: sender The model class. instance The actual instance being saved. Is "sender" the class of the model instance being saved? Is "instance" an instance of the sender model ? i.e. if I registered a signal receiver to receive post_save signals from the User model using signal.connect(), would "sender" be the User model and "instance" be the instance of the User model being saved ? -
How to set the global WEB_IMAGE and NGINX_IMAGE environment variables
I am following this tutorial and it says Set the global WEB_IMAGE and NGINX_IMAGE environment variables (export WEB_IMAGE = ? what exactly and where? on my local machine or in the droplet?) Add environment variables to a .env file (I created a .env file on the root directory and it is accessble by the Django settings - so this is done) Set the WEB_IMAGE and NGINX_IMAGE environment variables with so they can be accessed within the Docker Compose file I am not sure how to do these steps, can someone please explain? I am on ubuntu 20.04