Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I display all the users on my html page?
This piece of code gets me the required output in my python terminal views.py from django.contrib.auth.models import User userList =User.objects.all() print(userList) outputs this in the terminal <QuerySet [<User: brad>, <User: john>]> I know I have to iterate through the QuerySet but I am not able to link this view to my main page. So how can I get this on my main HTML page? -
Access table changes only by the creator - Django
I'm using a Django structure with a postgres database. In my system, one person owns a collection and has several employees. There is a set of settings in the owner panel, which is applied only by the person using the API. But I, the owner of this project, with the access I have to the database, I can change any settings that this person has made. How can I make it possible for only that person to make changes? Even I, who have access to the database, can not add or subtract these changes. -
Between Flask and Django which has better security features for Rest Api?
Between Flask and Django which has better security features for Rest Api -
Form Wont move down using Css
I have tried implementing some CSS to move my form up or down the page and I still cant get it to move and I don't seem to know why and I've tried using padding and margins and I still cant seem to get it to work and the css does appear on the page but nothing on it will move and they all just stay attached to the nav bar at the top of the screen. Attached is the html for the page and the CSS. Css .main2{ top:40px; margin-left:70px; width: 90%; height:75%; background-color: #36454F; position:fixed; padding-top: 100%; padding-bottom: 1%; } .contact-form { float:right; background-color:white; margin-right:10px; width: 30%; margin-top:28px; } Here is the html code <!DOCTYPE html> {% extends 'parasites_app/base.html' %} {% load static %} {% block content_block %} <link rel="stylesheet" type="text/css" href="{% static 'css/Contact.css' %}" xmlns="http://www.w3.org/1999/html"/> <div class="main" > <div class="main2"> <form id="user_form" class="contact-form" method="POST" action='/Contact/' enctype="multipart/form-data"> <div class="contact-container"> <h2>Contact Us</h2> {% csrf_token %} Email<input type="text" name="Email" value="" size="30" /> <br /> Question<input type="text" name="Quesstion" value="" size="50" /> <br /> <!-- Submit button--> <div> <button type="submit" class="submit-button">Send Request</button> </div> </div> </form> </div> </div> {% endblock %} -
Securing Webhooks in DJango
Wondering what library, video, or documentation I can be pointed towards. My goal is to secure the incoming webhook request through a username/password or secret etc. -
django.db.utils.IntegrityError: NOT NULL constraint failed: main_companyclass.FinancialYearEnd
I am running into the above-mentioned error when trying to run my app after creating a form that only updates 1 field. What I am trying to achieve is as follows: The user enters a client into the app and that saves it to the database, once that is done the client should be displayed on the checklist page where it will display some details about the client and show a checkbox (isdone_IT14) to say whether the clients' order has been completed. The problem is that it doesn't seem that when the user ticks the checkbox and saves it, it doesn't seem like its updating that entry in the model. I had created the below form to assist with that: class CompanyIT14Form(ModelForm): class Meta: model = CompanyClass fields= ['isdone_IT14'] But it is clearly not the correct solution. Does anyone know a better way to solve this error ? Please see the below code: Models.py: class CompanyClass(models.Model): #Company Only Fields CompanyName = models.CharField(max_length=50 , blank=False) RefNo = models.CharField(max_length=50 , blank=False ) FinancialYearEnd = models.DateField(auto_now=False, auto_now_add=False, null=False) #Contact Details ContactPerson = models.CharField( max_length=50, blank=False) EmailAddress = models.CharField(max_length=50, blank=False) #Services IT14 = models.BooleanField(default=True) # CheckList isdone_IT14 = models.BooleanField(default=False) def __str__(self): return ( self.CompanyName) … -
Communication between Django and React Native
This will be a very naive question. I am working on a website that I'm generating using Django. For now, the whole interaction with the sqlite database will be via the browser, so everything is fine. In the future, I would potentially like to generate mobile apps that basically do the same thing as the web interface does now. It would be nice to use React Native due to its cross-plattform compatibility. Will I be able to generate a React Native app that can communicate with a Django API in a save way, also with POST methods? I am far from being able to do that, just finding my way with Django, however I don't want to spend a lot of time on this Django web app now and later find out that what I did is not compatible at all with React Native. I'm sure this is an easy question for many of you. Best, Gero -
How to override the create method for a nested serializer for an APIView post request method?
I am trying to override the create() method for the following Serializer: serializers.py class TaggingSerializer(serializers.ModelSerializer): tag = TagSerializer() resource = ResourceSerializer() gameround = GameroundSerializer() user = CustomUserSerializer(required=False) class Meta: model = Tagging fields = ('id', 'user', 'gameround', 'resource', 'tag', 'created', 'score', 'origin') def create(self, validated_data): """Create and return a new tagging""" tags_data = validated_data.pop('tags') resources_data = validated_data.pop('resources') gamerounds_data = validated_data.pop('gamerounds') users_data = validated_data.pop('users') tagging = Tagging.objects.create(**validated_data) for tag_data in tags_data: Tag.objects.create(tagging=tagging, **tag_data) for resource_data in resources_data: Resource.objects.create(tagging=tagging, **resource_data) for gameround_data in gamerounds_data: Gameround.objects.create(tagging=tagging, **gameround_data) for user_data in users_data: User.objects.create(tagging=tagging, **user_data) return tagging def to_representation(self, data): data = super().to_representation(data) return data This is the JSON object I am trying to send: { "user": creator, "gameround": 1, "resource": 602, "tag": "Redtagtestpost", "created": "2022-12-12T15:19:49.031000Z", "score": 0, "origin": "" } However I keep getting various types of "JSON parse..." errors in Postman. I have tried using different fields for the other models and nothing seems to work. -
Django: add user on admin page using custom user model
I defined a custom user model in my Django project, which defines the 'email' as the unique identifier. I created a custom user creation form following the Django documentation and registered it in my admin.py. When I start the webserver, no errors are shown in the console. My problem is, that the add_form on the admin page does not show the 'email' field, but only 'username', 'password1' and 'password2' I read several how to's and tutorials and checked the Django documentation to resolve this issue and am affraid I am missing something. model.py # Custom User Account Model from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class CustomAccountManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, username, first_name, last_name, password=None, **other_fields): if not last_name: raise ValueError(_('Users must have a last name')) elif not first_name: raise ValueError(_('Users must have a first name')) elif not username: raise ValueError(_('Users must have a username')) elif not email: raise ValueError(_('Users must provide an email address')) user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, **other_fields ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, … -
Is it possible to use CheckConstraint on model instance in the django shell?
I have a model and want to apply a constraint on it to ensure only sensible values get to be stored in the model. The model along with the constraint I am using looks somewhat like this (simplified) from django.db import models class Task(models.Model): ACTION_CHOICES = ( ('UnderWay', 'UnderWay'), ('Processed', 'Processed'), ('Entrusted', 'Entrusted') ) action = models.CharField(max_length=20, default='UnderWay', choices=ACTION_CHOICES) entrusted_to = models.CharField(max_length=20, help_text='Name of the department/person entrusted to') # some other fields class Meta: constraints = [ models.CheckConstraint( check=( (models.Q(action='Entrusted') & (models.Q(entrusted_to__isnull=False) | ~models.Q(entrusted_to=''))) | ((models.Q(action='UnderWay') | models.Q(action='Processed')) & (models.Q(entrusted_to__isnull=True) | models.Q(entrusted_to=''))) ), #more complex conditions in actual name='constraint_on_et' ) ] def __str__(self): return f'{self.id} - {self.action}' Makemigrations and migrate ran successfully. But, when I try to create new instances through the shell, the constraint fails in cases that weren't meant to be. I looked at the coded constraint again and it looks fine to me. So, I tried to break the constraint(constraint_on_et) into simpler conditions to see which one actually fails. As the table is already populated, I am not able to check some specific parts of the constraint(they are always meant to fail on current data). Out of curiosity, I thought if I could apply a CheckConstraint, directly … -
How to pass all objects attributes to ListView
This is my detail view, I pass if a post is 'liked' and 'total likes' in context. I want to do the same in my List View for every object. class MemeDetailView(DetailView): model = Meme template_name = "memes/meme_detail.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) meme = get_object_or_404(Meme, id=self.kwargs['pk']) context['total_likes'] = meme.total_likes() liked = False if meme.likes.filter(id=self.request.user.id).exists(): liked = True context['liked'] = liked return context here is my ListView: class MemeListView(ListView): model = Meme paginate_by = 100 ordering = ['-created_at'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() return context How can I pass all objects 'total likes' and 'liked' to context? -
Apache Ubuntu - Can't host Django
I've been trying to get my Django REST project to work in Apache for the last couple of hours but all I'm getting is the Apache2 homepage. The url I need the Django server to work on. This currently just displays the default Apache2 page. hhhhhhhhh.stratoserver.net:8000 If I try any of the django paths like /admin or /api it gives me a 404 Not Found error. /etc/apache2/sites-available/st-backend.conf <VirtualHost *:8000> ServerAdmin webmaster@localhost ServerName hhhhhhhhh.stratoserver.net:8000 ServerAlias www.hhhhhhhhh.stratoserver.net:8000 DocumentRoot /var/www/st-backend # Point this to the wsgi.py in the same directory as your settings.py file WSGIScriptAlias / /var/www/st-backend/project/wsgi.py WSGIDaemonProcess st-backend python-path=/var/www/st-backend:/var/www/st-backend/stenv/lib/python3.8/site-packages WSGIProcessGroup st-backend Alias /static /var/www/st-backend/project/static <Directory /var/www/st-backend/project/static> Require all granted </Directory> <Directory /var/www/st-backend> <Files wsgi.py> Require all granted Allow from all </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> I've used a2ensite st-backend to enable the site, apachectl configtest to check syntax (which is ok) and restarted apache using sudo systemctl restart apache2.service. Everything else is default other than changing the port from 80 to 8000. Can anyone point out to me what's going wrong in the configuration file? I've checked all the paths multiple times and they're all valid paths. -
Wagtailmenus: how to access Page fields from first level menu?
I'm using Wagtailmenus 3.0.2. The documentation says: If the template is for rendering the first level of a main or flat menu, then menu_items will be a list of MainMenuItem or FlatMenuItem objects (respectively). In all other cases. it will be a list Page objects. (https://wagtailmenus.readthedocs.io/en/v3.0/rendering_menus/custom_templates.html) I'm using a FlatMenu with only one level. I need to access Page fields but it's not rendered in the template. When I use a multilevel menu, I can access Page fields inside the submenu without problem. I wonder if there is a way to access Page fields inside the first level menu. Thanks in advance for your help! -
I want to use the column defined in one table in another new table in SQL
I want to use the Phone column of extendeduser model in willpant model but when I add the phone column in willplant model and run command makemigrations its gives me two option as seen in Screenshot . I want to use the phone column data in Willplant model below. enter image description here enter image description here enter image description here -
Django: Including multiple forms leads to errors
Error: Some forms are sent as 'invalid', which does not create an entry in the database. Only FieldForm and ColorsForm are working -> all other do not send the submitted data even if i entered valid information What I did: I had multiple forms If I wanted to submit only one specific form with the Submit button, all of them were submitted directly. Found Proper way to handle multiple forms on one page in Django Tried to implement it in my views file: @login_required try: radius = request.user.fieldradius except FieldRadius.DoesNotExist: radius = FieldRadius(user=request.user) try: font_size = request.user.fontsize except FontSize.DoesNotExist: font_size = FontSize(user=request.user) try: change_color = request.user.colors except Colors.DoesNotExist: change_color = Colors(user=request.user) try: toggle_settings = request.user.togglesettings except ToggleSettings.DoesNotExist: toggle_settings = ToggleSettings(user=request.user) try: page_details = request.user.pagedetails except PageDetails.DoesNotExist: page_details = PageDetails(user=request.user) if request.method == 'POST': if 'form1_btn' in request.POST: form = FieldForm(request.POST, prefix='form1', instance=Field(user=request.user)) if form.is_valid(): obj = form.save(commit=False) obj.creator_adress = get_client_ip(request) obj.save() return redirect('/dashboard#5') elif 'form2_btn' in request.POST: togglesettings_form = ToggleSettingsForm( request.POST, prefix='form2', instance=toggle_settings) if togglesettings_form.is_valid(): togglesettings_form.save() return redirect('/dashboard/#panel1') elif 'form3_btn' in request.POST: radius_form = FieldRadiusForm( request.POST, prefix='form3', instance=radius) if radius_form.is_valid(): radius_form.save() return redirect('/dashboard') elif 'form4_btn' in request.POST: change_color_form = ColorsForm( request.POST, prefix='form4', instance=change_color) if change_color_form.is_valid(): change_color_form.save() return redirect('/dashboard') elif 'form5_btn' … -
Javascript. Weird Error with Server events
I'm pretty new in Javascript and having some weird error using Javascript Server Event with Django Framework. Check Code down below. Django: main_course_api.py This func returns server event back to front-end.... (working well): def send_data_as_stream_event(request): import json request_data = request.GET.get('list_of_courses') append_to_list(request_data) course_data = get_parsed_data(LIST_OF_COURSES['list_of_courses']) response = django.http.StreamingHttpResponse(json.dumps(course_data)) response['Content-Type'] = 'text/event-stream' return response urls.py path('get/stream/response/data/', main_course_api.send_data_as_stream_event, name='stream'), Main.js var evtSource = new EventSource('http://127.0.0.1:8000/get/stream/response/data/'); evtSource.onopen = function(event){ console.log('connected....') } evtSource.onmessage = function(event) { console.log('on message event..', event) console.log(event); } evtSource.onerror = function(err) { console.error("EventSource failed:", err); evtSource.close(); }; evtSource.onclose = function(code){ evtSource.close(); console.log('event source has been closed', code); } }); It is supposed to work, but it gives me such error in JS console every time after execution: main.js:74 EventSource failed: Event {isTrusted: true, type: 'error', target: EventSource, currentTarget: EventSource, eventPhase: 2, …}isTrusted: truebubbles: falsecancelBubble: f falsecancelable: falsecomposed: falsecurrentTarget: EventSource {url: 'http://127.0.0.1:8000/get/stream/response/data/', withCredentials: false, readyState: 2, onclose: ƒ, onopen: ƒ, …}defaultPrevented: falseeventPhase: 0path: []returnValue: truesrcElement: EventSource {url: 'http://127.0.0.1:8000/get/stream/response/data/', withCredentials: false, readyState: 2, onclose: ƒ, onopen: ƒ, …}target: EventSource {url: 'http://127.0.0.1:8000/get/stream/response/data/', withCredentials: false, readyState: 2, onclose: ƒ, onopen: ƒ, …}timeStamp: 3608.300000011921type: "error"[[Prototype]]: Event evtSource.onerror @ main.js:74 error (async) (anonymous) @ main.js:73 Looks like something wrong with asynchronous, but not really sure about the … -
how to get the TaskId in GET method in Django Rest framework
I'm trying to get the value in GET method However, it's returning only taskid as NONE. Is it possible to get the values in GET method Here, what I have tried views.py: @api_view(['GET']) def GetCurrentRunningActivityForAudit(request, UserID): if request.method == 'GET': print("current running activity--userid--", UserID) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,)) result_set = cursor.fetchall() TaskId = request.data.get('TaskId') print('TaskId in result current running activity--', TaskId) IsActive=GetCurrentSubTaskSTatus(TaskId) print("IsActive", IsActive) data = [] for row in result_set: TaskId=row[0] TaskName = row[1] Source = row[2] SID = row[3] type = row[4] data.append({ "TaskId": TaskId, "TaskName":TaskName,"Source":Source, "SID":SID, "type":type, 'IsActive':IsActive}) return Response(data[0]) def GetCurrentSubTaskSTatus(taskid): IsActive = 1 cursor = connection.cursor() cursor.execute('EXEC [dbo].[USP_GetCurrentTaskStatus] @taskid=%s',(taskid,)) result_set = cursor.fetchall() return IsActive -
How to document individual actions of a ViewSet using `drf-spectacular`?
Using DRF's built-in way of documenting the API, I was able to write a docstring like the following and each action was documented by its corresponding line: """ list: The list action returns all available objects. retrieve:The retrieve action returns a single object selected by `id`. create: The create action expects the fields `name`, creates a new object and returns it. """ I am in the middle of switching to the library drf-spectacular, which allows for an easy generation of OpenAPI conforming schemes. However, the same docstring is now rendered for every action, which makes my documentation really long and redundant. Is there a way that only the relevant part of the docstring is rendered for each action? -
Django: bootstrap styling is lost in my sidebar; hat is the best way to solve this?
I use bootstrap dashboard (https://getbootstrap.com/docs/4.1/examples/dashboard) as a base for my project. I have added form in the sidebar but 'bootstrap' styling is lost as you can see in picture below. I have tried different approach like crispy-form (what I currently use), django-widget-peaks, but result is not really good I think, maybe because part of CSS is override? For example, text in the "Select" is partially visible... I would like to be able to use bootstrap styling option like input-group-sm to decrease input size but it doesn't works... Thanks for your help -
Only list the connected object from the OneToMany Field instead of all objects
I have a very reasonable pagespeed inside the django admin interface when i open my "facility" objects. But if i open one of my "facility addresses" it will take more than 8 seconds to load. I imagine that this is caused by the fact that all existing facilities are being loaded into the dropdown of the OneToMany Field even though the facility is only connected to one address. How can i limit it so there is either no dropdown on these OneToMany Fields or that it only shows the current objects it is connected to? class Facility(models.Model): UUID = models.CharField(max_length=150, null=True, blank=True) Name = models.CharField(max_length=150, null=True, blank=True) class Meta: verbose_name_plural = "facilities" def __str__(self): return self.Name class FacilityAddress(models.Model): PrimaryAddress = models.CharField(max_length=50, null=True, blank=True) SecondaryAddress = models.CharField(max_length=50, null=True, blank=True) City = models.CharField(max_length=50, null=True, blank=True) RegionOrState = models.CharField(max_length=30, null=True, blank=True) PostalCode = models.CharField(max_length=20, null=True, blank=True) Geolocation = models.CharField(max_length=20, null=True, blank=True) AddressInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE, related_name='fa') class Meta: verbose_name_plural = "facility addresses" def __str__(self): return f"{self.PrimaryAddress} {self.City}" -
Facing this issue with creating a superuser for so long, please help me
While trying to execute this command (venv) sreekarsiddula@Sreekars-MacBook-Air bidgala % /Users/sreekarsiddula/piapps/venv/bin/python3 manage.py createsuperuser I am facing this issue.👇 {} /Users/sreekarsiddula/piapps/venv/lib/python3.9/site-packages/django/db/models/fields/init.py:1365: RuntimeWarning: DateTimeField UserInfo.verification_expiry received a naive datetime (2022-02-01 13:46:28.114225) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" {} ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1129) During handling of the above exception, another exception occurred: urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1129)> During handling of the above exception, another exception occurred: T File "/Users/sreekarsiddula/piapps/venv/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 174, in (receiver, receiver(signal=self, sender=sender, **named)) File "/Users/sreekarsiddula/piapps/bidgala/bidgala/accounts/views.py", line 391, in user_saved raise Exception("Unable to process the request") Exception: Unable to process the request Any help will be much appreciated, I am trying to resolve this. -
Why isn't Django serving staticfiles in production?
I am wondering the reason why Django does not serve the statifiles in production, when DEGUB = False. STATICFILES_DIRS We specify STATICFILES_DIRS to tell Django where to look for staticfiles that are tied up to a specified app. STATIC_ROOT We specify STATIC_ROOT to tell Django where to store the files once we run python manage.py collectstatic, so everystatic file is stored in the path specified in STATIC_ROOT. Assume that we set STATIC_ROOT = "staticfiles/". This means that once we run the collectstatic command, all the files that are inside STATICFILES_DIRS paths are going to be stored in "staticfiles/" STATIC_URL Finally we specify STATIC_URL as "prefix" to tell Djando where to look for staticfiles, for example in the HTML <link> tag, the url that we see is based on STATIC_URL value When we upload our project to the server, we upload the entire project, so every single file. Why can't Django serve staticfiles itself when running on server? As I just said, we upload the entire folder, so the files we uploaded are there (and the staticfiles too!). QUESTIONS I am just wondering, why do we have to specify the staticfiles based on server in production, when Django could do everything … -
Django aggregate and annotate to count by group - multiple levels
I have a model that looks like: class Foo(models.Model): bar = models.CharField(...) baz = models.CharField(...) Foo(bar="a", baz="x") Foo(bar="a", baz="x") Foo(bar="a", baz="y") Foo(bar="b", baz="y") And I want a queryset that will return the largest count of unique (bar, baz) pairs for each bar: [ {"bar": "a", "baz": "x", "count": 2}, {"bar": "b", "baz": "y", "count": 1}, ] Ideally this will all be done within a query, I've tried combinations of distinct, aggregate, annotate, to no avail and can't see how to do it other than run raw SQL which I want to avoid. I'm using the PostgreSQL as my database backend. -
TypeError: <lambda>() takes exactly 2 arguments (3 given)
i have a problem in this code in wsgi: if settings.UWSGI_DJANGO_WARMUP: application({ 'REQUEST_METHOD': 'OPTIONS', 'SERVER_NAME': '127.0.0.1', 'SERVER_PORT': 80, 'PATH_INFO': '/ping', 'wsgi.input': sys.stdin, }, lambda x, y: None) # call the entry-point function i get this error: TypeError: <lambda>() takes exactly 2 arguments (3 given) (4 additional frame(s) were not displayed) ... File "sentry_sdk/integrations/wsgi.py", line 116, in __call__ _sentry_start_response, start_response, span File "newrelic/api/wsgi_application.py", line 668, in _nr_wsgi_application_wrapper_ result = wrapped(environ, _start_response) File "django/core/handlers/wsgi.py", line 214, in __call__ start_response(force_str(status), response_headers) File "newrelic/api/wsgi_application.py", line 636, in _start_response response_headers + additional_headers, *args) File "sentry_sdk/integrations/wsgi.py", line 137, in _sentry_start_response return old_start_response(status, response_headers, exc_info) TypeError: <lambda>() takes exactly 2 arguments (3 given) is it in the lambda function why is it takes 3 arguments? -
i have multiple documents in MongoDB database i want to fetch them one by one and display in form of table using django
I have multiple documents in MongoDB database i want to fetch them one by one and show their data in the form of table using Django is there any tool I can use my MongoDB is as follows: my model code is as follows from django.db import models # Create your models here. class level(models.Model): time=models.DateTimeField(primary_key=True,default=0) status=models.CharField(max_length=50) level=models.DecimalField(max_digits=12,decimal_places=6) my views code to fetch data is as follows def generate(request): events_list=level.objects.all() return render(request,'result.html',{'res':events_list})