Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How am I misunderstanding Django's get_or_create function?
We have a Django project that has a bunch of experiments, and each experiment can have zero or more text tags. The tags are stored in a table, and there is a many-to-many relationship between experiments and tags: class Tag(models.Model): text = models.TextField(max_length=32, null=False, validators=[validate_unicode_slug], db_index=True, unique=True) class Experiment(models.Model): ... tags = models.ManyToManyField(Tag) If I add a tag to an experiment with get_or_create() it does the right thing, filling in the tag table and the joining table. If I remove the tag from the experiment with remove() it also does the right thing by removing just the row from the joining table and leaving the tag table intact. But if I later come to re-add the tag to the experiment, it throws a uniqueness constraint error because it's trying to re-add the tag to the tag table. E.g: tag, created = experiment.tags.get_or_create(text="B") experiment.tags.remove(*experiment.tags.filter(text="B")) tag, created = experiment.tags.get_or_create(text="B") # It fails the uniqueness test here. Removing the uniqueness constraint just means it adds a new tag with identical text. So is it possible to add and remove tags arbitrarily by just modifying the joining table if a tag already exists? -
how to send request to ocpp1.6 charger using django channel server
I created a django web application and i use django channel to establish connection with ocpp1.6 charger. in consumers.py in receive_json function im receiving chargers requests and sending response successfully, problem: i need to send request to charger from my django server like remote start transaction request, how i can becoz in consumers.py file the receive function is only send response when they receive data i want when a client from my front end click on start button then a request sent to charger for remote start transaction -
execution of the ".py" script on a django web page
I need to run a script (on python) that will output information to a web page (on django), now by writing a link to the script, I just get the output of the script text on the page index.html <html> <head> <title></title> </head> <frameset rows=100% > <frameset rows=76%,24% > <frameset cols=64%,36% > <frame name=reports src="{% url 'core:reports-name' %}"> <frame name=fg_log src= > </frameset> <frameset cols=64%,36% > <frame name=fp_log src= > <frame name=ls src= > </frameset> </frameset> </frameset> </html> **urls.py** from django.urls import path, include from . import views app_name = 'core' urlpatterns = [ path('', views.index, name='index'), path('reports', views.reports, name='reports-name') ] **views.py** from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.shortcuts import get_object_or_404, redirect, render User = get_user_model() #@login_required def index(request): template = 'core/index.html' return render(request, template) def login(request): pass #@login_required def reports(request): template = 'cgi/reports.py' return render(request, template) I was prompted that the solution should be at the nginx level, that with nginx you need to prescribe a condition for script execution on a web page, but I did not find a solution I only found a solution for PHP, but I couldn't make it under pyhton location ~ \.py$ … -
how to assign my profile user to be a User instance
i have 2 applications in django project "accounts" for managing user and authetications and the "BP" for managing the BusinessPlan every application have her own models, urls, and views this is accounts/models.py : class User(AbstractBaseUser): email = models.EmailField(unique=True, max_length=255) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' class Meta: app_label = 'accounts' def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin this is accounts/views.py def signup(request): form = RegistrationForm() if request.method == 'POST': registration_form = RegistrationForm(request.POST) if registration_form.is_valid(): user = registration_form.save(commit=False) user.is_active = True user.save() user_id=user.id return redirect(reverse('bp:profile',kwargs={'user_id':user_id})) return render(request,'signup.html',{'form':form}) this is bp/models.py : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #.....other fields.... ther is other fields like name, birthdate, phone, .... this is bp/views.py: def profile(request,user_id): if request.method =='POST': user=User.objects.get(id=user_id) form = NewProfileForm(request.POST) if form.is_valid(): profile=form.save(commit=False) profile.user=user profile.save() else: form=NewProfileForm() return render(request,'profile.html',{'form':form}) i create the user and it's done then i try to add the profile after validating every data it send me this message: how to fix it -
A lot of similar queries bcs of for loop Django
I have for loop in my get_queryset function and i'm parsing info from request into my django template but for some reason bcs i try to filter by GUID i got 21 similiar sql queries I was trying to get CleanSections before my for loop but that didnt help Any tips how can i solve that? views.py def get_queryset(self): session = requests_cache.CachedSession('budget_cache', backend=backend, stale_if_error=True, expire_after=360) url = config('API') + 'BUDGET' response = session.get(url, auth=UNICA_AUTH) response_json = None queryset = [] if response_json is None: print('JSON IS EMPTY') return queryset else: all_sections = CleanSections.objects.all() for item in response_json: my_js = json.dumps(item) parsed_json = ReportProjectBudgetSerializer.parse_raw(my_js) if parsed_json.ObjectGUID == select_front: obj = parsed_json.ObjectGUID else: continue for budget in parsed_json.BudgetData: budget.SectionGUID = all_sections.filter(GUID=budget.SectionGUID) budget.СompletedContract = budget.СompletedContract * 100 budget.СompletedEstimate = budget.СompletedEstimate * 100 queryset.append(budget) return queryset -
How to get radio button value using django without submit button
<body> <form action="" method="post"> {% csrf_token %} <input type="radio" name="course" value="C" />C <br> <input type="radio" name="course" value="CPP" />CPP <br> <input type="radio" name="course" value="DS" />DS <br> </form> {{res}} </body> views.py def user(request): if 'CPP' in request.POST: print("CPP") return HttpResponseRedirect(request.path_info) Is there any solution to pass values to the views when the radio button is checked when submit button is not there -
Linking To Related Articles In Django
I have a Django blog, and each article is associated with a certain category. On the detail page of each article, there is a card on the right side. This card has a header of "Related Articles" and has a list of the five most recent articles under that same category as the article currently being viewed. Below this list of related articles is a button that should link the user to all articles under that same category. But I can't seem to make the link to serve its desired purpose. On my index page, I can click on any category and get directed to a list of similar articles, but I can't achieve the same functionality from my detail page. How do I fix this? Below are the relevant codes. In my models.py, class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True, blank=True) class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name def save(self, *args, **kwargs): # generate a slug based on the post title self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Post(models.Model): image = models.ImageField() title = models.CharField(max_length=255) slug = models.SlugField(unique=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='posts', default='uncategorized') post = models.TextField() date = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, blank=True, related_name="post_likes") … -
ox_Oracle with database 11g Django problem with view name 'ORDER'
In my project im using cx_Oracle to connect and recive data from ORACLE 11g database. In database i have view 'ORDER' and every time im trying to make query with that name i have error ORA-01722: invalid number, even with RAW query. I cant change view name. Can anybody have solution ? Django ver. 3.2.18 cx_Oracle ver. 8.3.0 Instant Client Oracle 21.9 Error ocures even with raw querry. Models in Django are same as view shema. -
Django. How to remove duplicate requests in a Modelform
model. py class MyModel(models.Model): name = models.CharField() attribute1 = models.ForeignKey(ModelOne) attribute2 = models.ForeignKey(ModelOne) attribute3 = models.ForeignKey(ModelTwo) forms.py class MyModelForm(ModelForm): class Meta: model = MyModel fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ModelOne_choice = [(fields.id, fields.__str__()) for fields in ModelOne.objects.all()] self.fields['attribute1'].choices = ModelOne_choice self.fields['attribute2'].choices = ModelOne_choice My current model has many foreign keys including different attributes pointing to the same foreign key. django debug_toolbar shows about 10 requests when creating a form. How can this number be minimized? I have used ModelOne_choice for repeated foreign keys. Tried Raw requests. As I understand it, when a project is launched into production, such a number of calls to the database is very bad -
how to send a list of data with django swagger
hi I want to send a list of id in the form of: ["1", "2", "3"] with django swagger... i tried this way first: views.py @swagger_auto_schema(**swagger_kwargs["payment_expenses"]) @action(methods=["post"], detail=True, parser_classes=(FormParser, MultiPartParser)) def payment_expenses(self, request, pk): items = request.data["items"] print(items) but out put is in the form of ["1,2,3"] -
Why adding index to django model slowed the exectuion time?
I've added the index to my django model in order to make the queries on it a little bit faster but the execution time actually went up: from autoslug import AutoSlugField from django.db import models class City(models.Model): name = models.CharField(max_lenght=30) population = models.IntegerField() slug = AutoSlugField(populate_from="name") class Meta: indexes = [models.Index(fields=['slug'])] And I've used this function to calculate execution time for my CBV: def dispatch(self, request, *args, **kwargs): start_time = timezone.now() response = super().dispatch(request, *args, **kwargs) end_time = timezone.now() execution_time = (end_time - start_time).total_seconds() * 1000 print(f"Execution time: {execution_time} ms") return response Before adding indexes to Meta class the execution time on City.objects.all() in my CBV was: Execution time: 190.413 ms But after adding it it became: Execution time: 200.201 ms Is there any idea why that happens? Perhaps it is unadvisable to use indexes on slug fields? -
Django Docker Postgresql database import export
I have a problem with postgresql database. I just want to able to export and import database like .sql file. But when using command line I am able to get .sql database file but when I'm trying to import it to database it's giving syntax errors in sql file. I can try to fix syntax errors in sql file but I don't want to solve this problem it like that. I need to get exported sql file without any errors and to be able to import it without any issue. What can be a problem? Postgresql version:postgres:14.6 For example here is auto generated sql code by exporting db as sql file. it gives syntax error in this line : "id" bigint DEFAULT GENERATED BY DEFAULT AS IDENTITY NOT NULL, DROP TABLE IF EXISTS "core_contact"; CREATE TABLE "public"."core_contact" ( "id" bigint DEFAULT GENERATED BY DEFAULT AS IDENTITY NOT NULL, "first_name" character varying(50) NOT NULL, "last_name" character varying(50) NOT NULL, "company_name" character varying(50) NOT NULL, "email" character varying(128) NOT NULL, "message" text NOT NULL, "created_at" timestamptz NOT NULL, CONSTRAINT "core_contact_pkey" PRIMARY KEY ("id") ) WITH (oids = false); But, when I change it manually like that : "id" bigint NOT NULL, And … -
problem with creating APIView for celery flower dashboard
I have Django, DRF and React application with few endpoints. I'd like to create APIView that redirects user to flower pages. The flower urls should be hosted under www.myapp.com/flower. I've created docker container with django, react, celery-beats, celery-worker, flower and nginx images and I can run them normally however I am not sure how to do it on lcoud. I am using Azure App Service. I have 2 files in my nginx folder but: nginx.conf server { server_name myapp; location / { proxy_pass http://myapp.com/flower; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } Dockerfile FROM nginx:1.17.4-alpine RUN rm /etc/nginx/conf.d/default.conf ADD nginx.conf /etc/nginx/conf.d -
Post Form object has no attribute 'cleaned'
This is my Post Form from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' def clean_slug(self): return self.cleaned['slug'].lower() Here is my Traceback: Traceback (most recent call last): File "django\core\handlers\exception.py", line 56, in inner response = get_response(request) File "django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "django\views\generic\base.py", line 142, in dispatch return handler(request, *args, **kwargs) File "E:\Django Unleashed\suorganizer\blog\views.py", line 28, in post if bound_form.is_valid(): File "django\forms\forms.py", line 205, in is_valid return self.is_bound and not self.errors File "django\forms\forms.py", line 200, in errors self.full_clean() File "django\forms\forms.py", line 437, in full_clean self._clean_fields() File "django\forms\forms.py", line 452, in _clean_fields value = getattr(self, "clean_%s" % name)() File "suorganizer\blog\forms.py", line 11, in clean_slug return self.cleaned['slug'].lower() AttributeError: 'PostForm' object has no attribute 'cleaned' [26/Apr/2023 14:51:24] "POST /blog/create/ HTTP/1.1" 500 93820 -
Django LDAP Active Directory Authentification
Im trying to adjust my django project to connect to AD. Using libraries django-auth-ldap, ldap. Binding user is fine, creating and populating django user - ok. But in the end, authentification fails with next output: Binding as CN=bind,CN=Users,DC=ATK,DC=BIZ Invoking search_s('DC=ATK,DC=BIZ', 2, '(sAMAccountName=admin)') search_s('DC=ATK,DC=BIZ', 2, '(sAMAccountName=%(user)s)') returned 1 objects: cn=admin,cn=users,dc=atk,dc=biz Binding as cn=admin,cn=users,dc=atk,dc=biz Binding as CN=bind,CN=Users,DC=ATK,DC=BIZ cn=admin,cn=users,dc=atk,dc=biz is a member of cn=django-admins,cn=users,dc=atk,dc=biz Creating Django user admin Populating Django user admin Caught LDAPError while authenticating admin: OPERATIONS_ERROR({'msgtype': 111, 'msgid': 6, 'result': 1, 'desc': 'Operations error', 'ctrls': [], 'info': '000020D6: SvcErr: DSID-031007E5, problem 5012 (DIR_ERROR), data 0\n'}) My settings.py file is below: AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', "django.contrib.auth.backends.ModelBackend", ] AUTH_LDAP_SERVER_URI = "ldap://BORUM.ATK.BIZ" AUTH_LDAP_BASE_DN = "DC=ATK,DC=BIZ" AUTH_LDAP_BIND_DN = "CN=bind,CN=Users,DC=ATK,DC=BIZ" AUTH_LDAP_BIND_PASSWORD = "***" AUTH_LDAP_USER_SEARCH = LDAPSearch( AUTH_LDAP_BASE_DN, ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" ) # AUTH_LDAP_USER_DN_TEMPLATE = "cn=%(user)s,cn=users,dc=ATK,dc=BIZ" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 255, ldap.OPT_REFERRALS: 0, } AUTH_LDAP_USER_ATTR_MAP = { "username": "sAMAccountName", "first_name": "givenName", # "last_name": "sn", } AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "DC=ATK,DC=BIZ", ldap.SCOPE_SUBTREE, "(objectCategory=group)", ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn") AUTH_LDAP_REQUIRE_GROUP = "CN=django-admins,CN=Users,DC=ATK,DC=BIZ" AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_superuser": "CN=django-admins,CN=Users,CN=ATK,CN=BIZ", "is_staff": "CN=django-admins,CN=Users,DC=ATK,DC=BIZ", } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 Any ideas would be highly appreciated. Error number 000020D6 indicates that ERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD, I dont really understand how to treat that error, how binding … -
How to inner join two models in django?
I have two models: Available Options: class AvailableOptions(models.Model): name = models.CharField(max_length=20, default="") image = models.ImageField(upload_to=upload_to, blank=True, null=True) Stock: class Stock(models.Model): name = models.ForeignKey( AvailableOptions, on_delete=models.CASCADE, related_name="Stock") quantity = models.IntegerField(null=False, default="") created_at = models.DateTimeField(auto_now_add=True) How do i query and return response the two models? I want to return name , quantity from the second model and image from the first model. I tried this in my view (testview) but it only returned the second model fields. @api_view(['GET']) def testview(request): query = Stock.objects.select_related('name') data = serializers.serialize('json', query ) return Response(data) -
Django postgres migration issues when adding fields to existing models
I currently have a project in development. When trying to add new fields to existing models I am having issues with migrations which is causing me to worry about data loss. The errors I'm getting is that it says the fields don't exist when I can clearly see in the latest migrations file it has been added. I have never had this issue before when adding new fields and then pushing to the remote repository and then pulling it into production where I would then do the migrations. -
I need to prevent showing previous pages from my django app
Even after I logged out I'm still able to see my previous pages how to prevent the browser from showing this? I tried this piece of JavaScript code . Note: I used template inheriting and templates statically imported. function preventBack() { history.pushState(null, null, location.href); window.onpopstate = function () { history.go(1); console.log("worked") }; } window.onload = function() { preventBack(); console.log("worked call ") }; when I tried this "console showed worked call" but the 'worked' is not yet printed in console means wins=down.onpopState not worked what's the cause of this problem. I'm quiet new in Django feels like I tarped here!! -
django-keycloak refresh openID connect .well-known error
Hello everyone i really need help in a issue i faced while working on django-keyclock: you can see here the documentation thet I'm following: https://django-keycloak.readthedocs.io/en/latest/ I did the initial setup and I setup for remote user , then i configured the server and the realms in the django admin panel and everything looks good. but when i try to Refresh OpenID Connect .well-known I got this error in the image. And i think that /auth is the problem because when I remove it I got a json response. please if anyone can help me. and thank you in advance. [enter image description here][1] [enter image description here][2] [1]: https://i.stack.imgur.com/g09Jc.png [2]: https://i.stack.imgur.com/Bv1E1.png -
How can I deploy an app on Heroku that is not located in the root directory?
I've got a project that has a directory structure as such: ├── backend │ ├── backend-files.py │ └── procfile ├── docker-compose.yml └── frontend I want to be able to deploy the Python backend (Django) on Heroku. As you can see it is located in it's own directory. However, Heroku does not allow me to specify a subdirectory when pointing to a github repo. This means that I would need my backend code to be at the root level in order to use their CD pipeline features. Does anyone know of a way to modify my configuration in Heroku so that I can keep the directory structure as is? -
Django-allauth Redirect any unauthenticated user to login page
I’m developing a django project and my veiws are function based and using django-allauth for authentication. Now, I’m searching for a pattern to work on all project so that any unauthenticated user is redirected automatically to login page. An alternative way is to add @login_required() decorator over every view function but I don’t see that as logical method. -
Custom OrderingFilter Django REST + Vue
I'm working on backend part of project (Django REST). I have a task - to do sorting for the front (Vue). The frontend sends a key for sorting and a parameter for sorting. Example: GET /api/v1/stocks/?sort_key=FBS&sort_type=ascending GET /api/v1/stocks/?sort_key=FBS&sort_type=descending I guess it can be done with OrderingFilter and DjangoFilterBackend. Any suggestions will be helpful. my models.py class Stock(models.Model): class Meta: verbose_name_plural = "Stocks" verbose_name = "Stock" ordering = ("-present_fbs",) store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, verbose_name="Store") fbs = models.PositiveIntegerField(default=0, verbose_name="FBS") my views.py class StocksApi(ListModelMixin, GenericViewSet): serializer_class = StocksSerializer permission_classes = (IsAuthenticated,) pagination_class = StocksDefaultPagination def get_queryset(self): return Stock.objects.filter(store__user_id=self.request.user.pk).order_by("-fbs") -
TK to run django server on windows
I have windows server running Django as a CMD process. Some workers mistakenly closing it. I want to switch to TK running the Django server and put output on screen. How safe is that ? How do I close the django properly ? class TextRedirector(object): def __init__(self, widget, tag="stdout"): self.widget = widget self.tag = tag def write(self, str): self.widget.configure(state="normal") self.widget.insert("end", str, (self.tag,)) self.widget.see(tk.END) self.widget.configure(state="disabled") class TkApp(tk.Tk): def __init__(self): tk.Tk.__init__(self) toolbar = tk.Frame(self) toolbar.pack(side="top", fill="x") # set window size self.geometry("500x200") self.title("DJANGO") self.text = tk.Text(self, wrap="word") self.text.pack(side="top", fill="both", expand=True) self.text.tag_configure("stderr", foreground="#b22222") self.text.yview("end") self.iconbitmap("activity.ico") sys.stdout = TextRedirector(self.text, "stdout") sys.stderr = TextRedirector(self.text, "stderr") self.protocol('WM_DELETE_WINDOW', self.on_close) self.run() def on_close(self): response = tkinter.messagebox.askyesno('Exit', 'Are you sure you want to exit?') if response: try: # KILL THE DJANGO PROCESS .... finally: sys.exit(0) def run(self): # RUN THE DJANGO PROCESS .... if __name__ == '__main__': app = TkApp() app.mainloop() will this work ? I also need to tell the django to close nicely (same as I would click the X button on command line) Instead: I want: -
Scan python link and iframe it?
i want to execute one python code and try to get output in browser import os tools=os.popen('pip list | seashells').read() output is this link serving at https://seashells.io/v/rWXx9XvF how to iframe the link generated in terminal ? i try to store this seashell generated link in python veriable and iframe in html code but cuould not do it? i neeed help!! -
ModuleNotFoundError: No module named 'phone_verify.views'
I am using django-phone-verify in my drf project to send otp and phone call for sign in. When i want to import start_verification from phon_verify.views this error is showing"ModuleNotFoundError: No module named 'phone_verify.views" views.py from rest_framework.decorators import api_view from rest_framework.response import Response from phone_verify.views import start_verification @api_view(['POST']) def sign_in_sms(request): phone_number = request.data.get('phone_number') if not phone_number: return Response({'error': 'Phone number is required'}, status=400) start_verification(phone_number, method='sms') return Response({'success': 'Verification started'}) @api_view(['POST']) def sign_in_phone_call(request): phone_number = request.data.get('phone_number') if not phone_number: return Response({'error': 'Phone number is required'}, status=400) start_verification(phone_number, method='call') return Response({'success': 'Verification started'}) urls.py from django.urls import path, include from phone_verify.urls import urlpatterns as phone_verify_urls from django.urls import path from sms.views import sign_in_sms, sign_in_phone_call urlpatterns = [ path('api/', include('sms.urls')), path('phone-verify/', include(phone_verify_urls)), path('sign-in/sms/', sign_in_sms), path('sign-in/phone-call/', sign_in_phone_call), ] settings.py INSTALLED_APPS = [ 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'phone_verify', 'sms', ] PHONE_VERIFICATION = { 'FROM_NUMBER': 'my number', 'TWILIO_ACCOUNT_SID': 'my sid', 'TWILIO_AUTH_TOKEN': 'my token', }