Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
tailwindcss config with django
I can't figure out how to config tailwindcss with django. I might just be doing the tailwind side wrong but I know I've configured my django static files correctly. I've watched every video I can find and none of them address my specific problem. An explanation of how tailwind config works on a low level would also be helpful so I could diagnose the problem myself. thanks. error message file structure and config file -
How to conditionally remove form field=required
It's simple to require a field based on the state of another: class FooForm(forms.Form) foo = forms.BooleanField() bar = forms.CharField(required=False) def clean(self): if self.cleaned_data.get('foo') and not self.cleaned_data.get('bar'): raise forms.ValidationError('With foo you must have bar') How can I do the reverse and remove a field requirement instead? E.g. class FooForm(forms.Form) foo = forms.BooleanField() bar = forms.CharField(required=True) def clean(self): if not self.cleaned_data.get('foo'): # No foo, no bar required del bar.required?? -
pytest -n auto + mariadb + m1 mac too slow
Issue Running pytest -n auto on my system with mariadb is taking significantly longer the running pytest Image of result and time System specs System specs Package versions mariadb Ver 15.1 Distrib 10.8.3-MariaDB python 3.9.6 pytest 7.1.3 MariaDB config file [client] port = 3306 socket = /tmp/mysql.sock [mysqld] port = 3306 socket = /tmp/mysql.sock back_log = 50 max_connections = 100 wait_timeout = 256 max_connect_errors = 10 table_open_cache = 2048 max_allowed_packet = 16M binlog_cache_size = 512M max_heap_table_size = 512M read_buffer_size = 64M read_rnd_buffer_size = 64M sort_buffer_size = 64M join_buffer_size = 64M thread_cache_size = 8 thread_concurrency = 8 thread_stack = 240K query_cache_size = 128M query_cache_limit = 2M ft_min_word_len = 4 default-storage-engine = InnoDB transaction_isolation = REPEATABLE-READ tmp_table_size = 512M log-bin=mysql-bin binlog_format=mixed slow_query_log long_query_time = 2 server-id = 1 # INNODB options innodb_buffer_pool_size = 4G innodb_buffer_pool_instances = 8 innodb_data_file_path = ibdata1:10M:autoextend innodb_write_io_threads = 8 innodb_read_io_threads = 8 innodb_thread_concurrency = 16 innodb_flush_log_at_trx_commit = 1 innodb_log_buffer_size = 1GB innodb_change_buffering = all innodb_change_buffer_max_size = 25 innodb_log_file_size = 512M innodb_log_files_in_group = 3 innodb_max_dirty_pages_pct = 90 innodb_lock_wait_timeout = 256 [mysqldump] quick max_allowed_packet = 50M [mysql] no-auto-rehash [mysqlhotcopy] interactive-timeout [mysqld_safe] open-files-limit = 8192 Additional info All packages and apps are running natively and not through rosetta -
django autofil with the pk page
I would like to add documents to an employee's profile in a form but I would like the form to automatically select the id or the (pk) of the employee's page, anyone have the solution? view.py def createDocument(request): forms = documentForm() if request.method == 'POST': forms = documentForm(request.POST, request.FILES) if forms.is_valid(): forms.save() return redirect('/employe') context = {'forms':forms} return render(request, 'accounts/document_form.html', context) add document form -
strptime() argument 1 must be str, not DeferredAttribute
I am heaving trouble here, am making a travel and visa website, am trying to make sure we know each appointment 10 days in advance. So I made a model property that would help me compare dates, but am having trouble error after error here is the model field class customer(models.Model): first_name = models.CharField(max_length=255, default='') last_name = models.CharField(max_length=255, default='') biometry_date = models.DateField(blank=True, default='', null=True) @property def is_due(self): datetime_object = datetime.strptime(Profile.biometry_date, '%Y-%m-%d') t2 = datetime.now().date() t3 = timedelta(days=30) return datetime_object - t2<= t3 and in the Html template {% if customer.is_due %} <td class="text-right"> <span class="badge badge-danger">{{ profile.biometry_date }}</span> </td> {% else %} <td>{{ customer.biometry_date }}</td> {% endif %} Please help me Thanks -
asyncio.create_task() is not running asynchronously in async view function
I'm creating an async function to upload a video. The goal is to run the video upload asynchronously in the background without making the user wait. The user will be redirected to another page while the video is uploading. Following instructions in Python's asyncio docs, I'm using create_task() as that seems to be the simplest solution. In the following code, it works but it is not running asynchronously. HttpResponseRedirect is not running until after the video is fully uploaded. I also inserted 2 lines to check whether upload_video() is running asynchronously and it is. print('before') and print('after') are both printed to the console before the upload_video function completes. However, the final HttpResponseRedirect() does not run until all the code has been executed. async def my_async_func(request): if request.method == 'POST': video = request.FILES['video'] print('before') asyncio.create_task(upload_video(video)) print('after') return HttpResponseRedirect(... somewhere) async def upload_video(video): ... Basically despite all the async syntax & logic I wrote, the function is still running like a typical synchronous django view function. Why is this? What do I need to change to make upload_video() run asynchronously and return HttpResponseRedirect() without waiting? P.S. I also tried replacing create_task() with ensure_future() but it gave me the same result - the … -
Display a product whose ID is passed as a parameter
I would like to retrieve the product whose 'id' is passed as a parameter, how do I do this? For example here I passed the id equal to 1 Note I don't use a model but a dictionary def cart_add(request, id): dico={"produits":[{'id':1,'name':'pomme de terre','price':1250}]} mes_produits=dico['produits'] cart = Cart(request) mes_produits['id']=id product=mes_produits['id'] cart.add(product=product) return render(request, 'cart/cart_detail.html') i get this error : list indices must be integers or slices, not str -
How to send data to Django from Kafka (python library)?
i am trying to implement an app that streams Data from a message bus. I have chosen to use Pykafka as a bus but i dont know if it can connect with my Django app. Using Django Channels all the solutions i have found use Redis as a message queue but i want to create something more scalable. Any advice even a basic one can be helpful, thaks in advance. -
How to parse the many values of one-to-many relationship into HTML template in Django?
I have a one-to-many relationship in Django as such: class Listing(models.Model): title = models.CharField(max_length=60) class Images(models.Model): listings = models.ForeignKey(Listing, on_delete=models.CASCADE) image_urls = models.URLField(max_length = 200) I have the following view defined: from .models import Listing, Images def index(request): All_Listings = Listing.objects.filter(isActive=True) return render(request, "index.html", { "All_Listings": All_Listings, "Images" : Images }) Now for each listing I want to show all related images in my HTML. I have tried to do the following: {% extends "layout.html" %} {% block body %} {% for listing in All_Listings %} <h2>{{ list(Images.objects.filter(listings_id=2)) }}<h2> {% endfor%} {% endblock %} (If this works, than later on I will replace 2 with listing.id) This returns the following error: Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '(Images.objects.filter(listings_id=2))' from 'list(Images.objects.filter(listings_id=2))' However, when I run this from the terminal it works: >>> list(Images.objects.filter(listings_id=2)) [<Images: https://www.kettererkunst.com/still/kunst/pic570/531/422000352-4.jpg>, <Images: https://www.kettererkunst.com/still/kunst/pic570/531/422000352-1.jpg>] How should I approach this? -
RuntimeWarning: DateTimeField Lesson.startdate received a naive datetime (2022-09-18 00:00:00) while time zone support is active. RuntimeWarning)
RuntimeWarning: DateTimeField Lesson.startdate received a naive datetime (2022-09-18 00:00:00) while time zone support is active. RuntimeWarning) def auto_send_notification(request): today = date.today() substatus = SubscribeEmailModel.objects.filter(topic__startdate=today, sent_mail=False) Models.py class Lesson(models.Model): startdate = models.DateTimeField(auto_now=True, null=True) enddate = models.DateTimeField(auto_now=True,null=True) -
Unable to connect. Error: self signed certificate (Retool, Heroku and Django)
I'm doing a Django project using Heroku and Retool for my database and tests. Still, when I try to connect my Retool resource to the Heroku database it shows the error "Unable to connect. Error: self-signed certificate". Has this happened to anyone else? Thanks! PS.: I need to connect using SSL -
Dynamically load data into a Django Template from a Django Modal without page refresh
I have the following Django model and I use the first 3 fields to generate a tree-view in the template as shown below. class operationTemplates(models.Model): templateID = models.IntegerField(primary_key = True) templateCategory = models.CharField(max_length=255, blank=True, null=True) templateName = models.CharField(max_length=400, blank=True, null=True) templatePreopBundle = models.TextField( blank=True, null=True) templateIndication = models.TextField( blank=True, null=True) templatePosition = models.TextField( blank=True, null=True) templateProcedure = models.TextField( blank=True, null=True) templateClosure = models.TextField( blank=True, null=True) templatePostOpInstructions = models.TextField( blank=True, null=True) <!-- tree view --> <ul class="tree"> <li> <input type="checkbox" id="c0" /> <label class="tree_label" for="c0">Vascular Surgery</label> <ul> {% for k, v in group.items %} <li> <input type="checkbox" id="c{{forloop.counter}}" /> <label for="c{{forloop.counter}}" class="tree_label">{{ k }}</label> <ul> {% for x in v %} <li><span class="tree_label"><a href="{{ x.templateID }}">{{ x.templateName }}</a></span></li> {% endfor %} </ul> </li> {% endfor %} </ul> </li> </ul> <!-- tree view end--> Tree-View generated dynamically using date from the above modal When the user clicks on a particular leaf of the tree, I want to be able to query and display all the fields relevant to that record from the Danjo Model without a page refresh. What is the best way to achieve this? Do I need to use JSON/JavaScript? Or is there an elegant way to do it just … -
<p> tag has padding around it
I have form with multiple inputs in it: <input type="text" placeholder="First name" class="input_1_error input_1"> <input type="text" placeholder="Last Name" class="input_2" name="last_name" size="1" value="{{ data.last_name }}"> <input type="text" placeholder="Username" class="input_3" name="username" size="1" value="{{ data.username }}"> <input type="text" placeholder="Email" class="input_6 input_6_error" name="email" size="1" value="{{ data.email }}"> but when I add <p>Please enter your email</p> under email it creates much more space than I would want -
How to design Student QRcode meal card system using Django
Hello Django developers, I want to build student cafeteria system using QRcode scanner. Here is how it should work. Student scann there meal card, then the system displays student info and also it should mark served. Then the system count the number of served students. The system should ignore or show red labeled text if there is rescanning. So here i who can help me what things i have to consider to get the django model. Thank you -
Error in running a project regarding virtual environment and "DJANGO_SECRET_KEY" in VS code
I want to run a project from gitlab on my local machine. I cloned the project, created a virtual environment and activated it. When I want to run without debugging I got this error: File "c:\Users\ME\Desktop\test\z_tool\settings.py", line 28, in SECRET_KEY = env.str('DJANGO_SECRET_KEY') File "c:\Users\ME\Desktop\test\myenv\lib\site-packages\environs_init_.py", line 110, in method raise EnvError('Environment variable "{}" not set'.format(proxied_key or parsed_key)) environs.EnvError: Environment variable "DJANGO_SECRET_KEY" not set The output of this project is a form, how can I solve this error to get the output? -
CSRF token verification error in django admin using SSL, nginx
I have a csrf token error when trying to log in to the django admin in production after adding SSL. So if I use the configuration below without ssl everything works fine: upstream app_server { server unix:/home/app/run/gunicorn.sock fail_timeout=0; } server { listen 80; # add here the ip address of your server # or a domain pointing to that ip (like example.com or www.example.com) server_name 107.***.28.***; keepalive_timeout 5; client_max_body_size 4G; access_log /home/app/logs/nginx-access.log; error_log /home/app/logs/nginx-error.log; location /static/ { alias /home/app/static/; } # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } But if I change to configuration do listen SSL when filling in any form on the page I get the csrf_token error. My configuration nginx using SSL: upstream app_server { server unix:/home/app/run/gunicorn.sock fail_timeout=0; } server { #listen 80; # add here the ip address of your server # or a domain pointing to that ip (like example.com or www.example.com) listen 443 ssl; server_name example.com; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; keepalive_timeout 5; client_max_body_size 4G; access_log /home/app/logs/nginx-access.log; error_log /home/app/logs/nginx-error.log; # Compression config gzip on; gzip_min_length 1000; gzip_buffers 4 32k; gzip_proxied … -
In a Django Rest Framework view, does request.user make a database call or the database call happens before the request reaches the view?
I need to retrieve some information about my users and I am trying to avoid making unnecessary database calls. The information I need is stored in three models: User, UserProfile and Membership. Both UserProfile and Membership have a OneToOne relationship with the User model. I know that I can use select_related() to retrieve related models from the database in a single call. So I could do something like: User.objects.select_related('userprofile').select_related('membership').get(id=request.user.id) But that must not be correct, because if I am using some user information to do the query, it means I already retrieved this information in a previous call. So what would be the best way to get this information minimising database calls? Would it be even possible to get the information from these 3 models in a single call? -
How do I search 2 tables in
I am continuing to learn Django as a newbie.....I would like some direction in relation to 1 search query against two tables that hold the same headers such as customer names. So table 1 is customer names from 2022 and table 2 is customer names from 2021. I can create the models / admin and URL and set the project up. How do I create a query to search both tables at the same time and display the result? View.py def index(request,): q = request.GET.get('q') if q: #this is what is searched against.....ie the columns in our model.py vector = SearchVector('name') #This is the value the user is searching for: query = SearchQuery (q) # customers = customer.objects.filter(name__search=q) # customers = customer.objects.annotate(search=vector).filter(search=query) customers = customer1.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.001).order_by('-rank') else: customers = None context = {'customers': customers} return render(request, 'index.html', context) Index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>GAEN</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> </head> <body> {% include 'navbar.html' %} <div class="container"> {% block content %} <br><br><br><br> <form> <div class="mb-3"> <label for="Search Query" class="form-label "> <h3>db Search Query</h3> </label> <br><br> <input type="text" class="form-control" aria-describedby="#" name="q"> <br><br> <button type="submit" class="btn btn-primary ">Submit</button> <button type="submit" class="btn btn-danger">Reset</button> </div> </form> {% … -
Django ManyToManyField does not get cleared
I am using a ManyToManyField and want to be able to clear it. This is my current code (Yes, I do override the save method of the same Object Class) def save(self, *args, **kwargs): if self.maxparticipants == 0: self.participants.clear() super(Event, self).save(*args, **kwargs) What it does:It checks if the maxparticipant count is 0 (so there is no participant allowed) and if it's true it should remove every participant from the m2m. When printing self.participants.all() I get Queryset([]) - it works fine.... in theory because it won't get written to the database :/ If you need more details just add a comment :) -
google login in django do not give email and username instead give first_name and last_name in django_rest_social_oauth2 and update value superuser
using google login in django do not give email and username instead give first_name and last_name only and update that in my superuser in django_rest_social_oauth2 SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'] SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = True SOCIAL_AUTH_GOOGLE_OAUTH2_USER_FIELDS = ['first_name', 'last_name', 'email','username'] AUTHENTICATION_BACKENDS = ( # Facebook OAuth2 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', # Google OAuth2 'social_core.backends.google.GoogleOAuth2', # django-rest-framework-social-oauth2 'rest_framework_social_oauth2.backends.DjangoOAuth2', # Django 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_USER_MODEL = '<custom user model>' -
NameError: name 'playground' is not defined
I am beginner. I am trying to learn Django. But I face a problem. I defined app name inside my project file but django did not found it. I am using Atom as a Code Edittor. Please Any one help me..enter image description here this is my code path('playground/',include(playground.urls)) File "C:\Users\Hasan\Documents\Django\STOREPRONT\STOREPRONT\urls.py", line 8, in path('playground/',include(playground.urls)) NameError: name 'playground' is not defined -
I am trying to get POST request but django response with GET request
I am trying to get the post request and i have tried everything it is still getting me get requests. Please Help. I have tried using that i saw in other problems displayed here. but it is not working for me. {% csrf_token%} Item name {{form.item_name}} Quantity {{form.quantity}} <div class="form-group"> <label for="address">Address</label> {{form.address}} </div> <div class="modal-footer d-flex justify-content-center"> <button type="submit" id="submit" class="btn btn-success" data-dismiss="modal" >Donate</button> </div> </form> This is my view file #this is my view @login_required(login_url='loginPage') def home(request): form = DonateForm() print(request.user.id) get_user = user_info.objects.get(id=request.user.id) print('Inside Home View') print(get_user) print(request) if request.method == 'POST': form = DonateForm(request.POST) print('Inside Home Page') if form.is_valid(): print('Form is valid!!') user = form.save() Donate.objects.create(user_name = user,item_name=form.cleaned_data['item'],quantity=form.cleaned_data['itemquantity']) else: messages.add_message(request,messages.INFO,'Your details are Incorrect!!') else: print('No Post Request!!') return render(request,'donate/home.html',{'form':form,'get_user':get_user}) Here is my Models.py class Donate(models.Model): user_name = models.ForeignKey(user_info,on_delete=models.CASCADE) item_name = models.CharField(max_length=30,null=False , blank=False, default ="None") quantity = models.IntegerField(null=False,blank=False,default=0) address = models.CharField(max_length=100 , null=False , blank= False, default="None") def __str__(self): return f"{self.user_name.user.username} donated {self.item_name}" -
Django - call Manager with multiple inherited classes
So I have this class that helps me override the update method of a queryset: class QuerySetUpdateOverriden(QuerySet, object): def update(self, *args, **kwargs): super().update(*args, **kwargs) if hasattr(self, 'method_from_object'): self.method_from_object() return and here's my class where I use it: class MyObject: objects = QuerySetUpdateOverriden.as_manager() def method_from_object(self): print("called") the print statement is never reached. And I get why - the objects field doesn't inherit MyObject too. So, the question is - how can I make it inherit MyObject so method_from_object will be called? Thanks. -
How to get the file object in `request.data` in Django?
(1) Upload a tar file. (2) How to get the file object in request.data? Thanks. class AlbumViewSet(viewsets.ModelViewSet): @action(methods=['POST'], detail=False, url_path='upload-album') def upload_album(self, request): # Upload one tar file. logging.error("----> request.data = {}".format(request.data)) -
Ifc.js: wasm streaming compile failed: LinkError: import object field 'a' is not a Memory
I am reading IFC files and ifc.js seemed like a solid option although I am not so experienced with javascript but I thought it could be a good opportunity to learn about it. I followed the documentation example that can be food here ``https://ifcjs.github.io/info/docs/Hello%20world```. I packed the app inside of a django project and everything is fine until I try to load up a file. I am getting the following error: RuntimeError: abort(LinkError: import object field 'a' is not a Memory). Build with -s ASSERTIONS=1 for more info. On my browser debugger, the error links to the following class of my bundle.js file class IFCLoader extends Loader { constructor(manager) { super(manager); this.ifcManager = new IFCManager(); } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(scope.manager); this.onProgress = onProgress; loader.setPath(scope.path); loader.setResponseType('arraybuffer'); loader.setRequestHeader(scope.requestHeader); loader.setWithCredentials(scope.withCredentials); loader.load(url, async function (buffer) { try { if (typeof buffer == 'string') { throw new Error('IFC files must be given as a buffer!'); } onLoad(await scope.parse(buffer)); } catch (e) { if (onError) { onError(e); } else { console.error(e); } I have no clue how to correct this issue and any help would be highly appreciated. I am happy to post additional files or …