Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
please help find free online resources on django
I am going to build a webapp that users can send and receive messages and files to each other can you please give me some free resources -
Django - Custom queryset to filter for a field in the models.py
In my model I want to filter out the ForeignKey in this case based off a value in that same model so anytime that field is used, in forms, views etc it shows the specific list instead of all objects. class PersonModel(models.Model): person_type = models.CharField(max_length=50, null=True, blank=True) person = models.ForeignKey( "self", related_name="person_model", on_delete=models.SET_NULL, null=True, blank=True, limit_choices_to={"person_type": "adult"}, ) This isn't working but it's the latest code I have. I'm hoping there is a simple way I can run a custom query against the "person" field such as the example below? class PersonModel(models.Model): person_type = models.CharField(max_length=50, null=True, blank=True) person = models.ForeignKey( "self", related_name="person_model", on_delete=models.SET_NULL, null=True, blank=True, queryset=PersonModel.objects.filter(person_type="adult"), ) -
django-globals not working (_thread._local object has not attribute 'user')
I installed the library django-globals from here: https://pypi.org/project/django-globals/ I followed the instructions, by adding the library to middleware and to installed apps: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_globals.middleware.Global', ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'team_members', 'Lib_Files', 'manage_user_credentials', 'create_new_matter', 'setup_new_matter', 'django.contrib.humanize', 'ebhealthcheck.apps.EBHealthCheckConfig', 'health_check', 'health_check.db', 'health_check.cache', 'health_check.storage', 'checklist', 'django_globals', ] Then I added the following import statement into one of my models: from django_globals import globals Now, I want to access my user's data. As a test, I put the following code in the above model: print(globals.user) I get an error: '_threads._local' object has not attribute 'user' Has anyone else tried to use the django-globals library? -
Why do I get "'No module named" error with my own package?
I have a new Django project, but I am failing to get the makemigrations to complete, because I get the error ModuleNotFoundError: No module named 'sare.formats'. I have had this error before when I forget to install a package required in the code, but this sare.formats module is one made by me, in this same project. I have three apps in the project: sare, formats and users, and the project is named sare. The error ocurrs in the line from sare.formats import System in my users.models. In the 'INSTALLED_APPS' section of my settings.py there are, in that order, among other packages: 'sare', 'formats', 'users', I would think that because 'users' is included in the installed apps AFTER 'formats', this issue wouldn't exist, so I don't know what am I not aware of. When I type from sare.formats import System, the IDE autocompletes everything, so I would asume the app is correctly typed and included. -
Why is the django logging-config not being applied to all logger-instances?
Python 3.8, Django 3.0 I use docker-compose logs to display and process the logs of a container with django. To ensure that all of the output has the same format, I define LOGGING inside of settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'detailed': { 'format': '{levelname} [{asctime}]{name} : {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level': env('DJANGO_LOG_LEVEL'), 'class': 'logging.StreamHandler', 'formatter': 'detailed' }, }, 'loggers': { '': { 'handlers': ['console'], 'propagate': False, 'level': 'DEBUG', }, 'django': { 'handlers': ['console'], 'propagate': False, 'level': env('DJANGO_LOG_LEVEL'), }, # django.template and django.backends must not use DEBUG-level, since it is buggy 'django.template': { 'propagate': True, 'level': 'INFO', }, 'django.db.backends': { 'propagate': True, 'level': 'INFO', }, # use same format for logs from uvicorn 'uvicorn': { 'handlers': ['console'], 'propagate': False, 'level': 'INFO', }, } } However, when running the container I get the following output in the logs: django_1 | INFO [2020-04-28 16:00:25,482]uvicorn.error : Started server process [16] django_1 | INFO [2020-04-28 16:00:25,482]uvicorn.error : Waiting for application startup. django_1 | INFO [2020-04-28 16:00:25,482]uvicorn.error : ASGI 'lifespan' protocol appears unsupported. django_1 | INFO [2020-04-28 16:00:25,482]uvicorn.error : Application startup complete. django_1 | WARNING: Detected file change in 'myproject/settings.py'. Reloading... django_1 | INFO [2020-04-28 16:04:01,080]uvicorn.error … -
ERROR: ModelViewSet in Django Rest Framework does not accept PUT or PATCH methods but accept GET and POST
This is the view from a Meal app of a delivery project, I am using Django and Django Rest Framework. I am trying to update a Meal instance, but PUT and PATCH methods are not allowed in the view. The url is working (already used in GET and POST), the request.data is been sent correctly. What's my error? Error message shown in postman: { "detail": "Method \"PATCH\" not allowed." } views/meals.py code: '''Meal views.''' # Django REST Framework from rest_framework import mixins, status, viewsets from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.generics import get_object_or_404 # Serializers from meals.serializers import MealModelSerializer # Models from meals.models import Meal from users.models import Store class MealViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): '''Meals view set. ################################################################################# Http methods and the URLs: GET /stores/<store_slugname>/meals/ (list Store meals) POST /stores/<store_slugname>/meals/ (create Stores meal) ###################################################################################### ''' serializer_class = MealModelSerializer lookup_field = 'slugname' search_fields = ('slugname', 'name') # Method call every time this MealViewSet is instanced def dispatch(self, request, *args, **kwargs): '''Verify that the store exists. Add the URL input <store_slugname> to the Meal model field store(FK). ''' store_slugname = kwargs['store_slugname'] self.store = get_object_or_404(Store, store_slugname=store_slugname) return super(MealViewSet, self).dispatch(request, *args, **kwargs) def get_queryset(self): '''Get Store's available meals''' return … -
Is there a efficient substitute to my django code?
def redirectory(request): if request.user.is_Type_A: return redirect("is_Type_A_views")#This loads Type_A html page elif request.user.is_Type_B: return redirect("is_Type_B_views")#This loads Type_B html page elif request.user.is_Type_C: return redirect("is_Type_C_views")#This loads Type_C html page Hi, i've created a log in function in django views.py that checks if a user is_Type_A or is_Type_B or is_Type_C and logs in the user to their custom pages based on their boolean fields True or False. I didn't want to use filters because the account users must have access to different function on the views.py and I didn't want to use conditional statements on the html page because I dont want to confuse myself and other people so I've created that code instead. So its basically a redirectory function. my question is, is that code efficient? can a Server use that single code and handle multiple login requests? And if not, is there a more efficient substitute code that I can use? -
How can I open File location in django project
I tried to open file location in django project with this code. <a href="C:\Users\development\SmartSearch Project\Data" target="_explorer.exe">Open Location</a> It's working in normal web pages. its not working in django project. -
How to filter from ManyToManyField?
In array_from_B field I would like to have just the results from array field of class B because I'm getting the whole object as of right now. Can someone please help? class A: name = models.CharField() class B: name = models.ForeignKey(A) array = ArrayField(models.CharField()) class C: array_from_B = models.ManyToManyField(B) Thank you in advance -
How the form_Valid function works in django?
What is this form object on the return line,is it the form object recieved by the submission of a form ? . and since we are returning it with return super().form_valid(form). can it be accessed like context variables ? from the template represented by the success_url .also form_valid points to success_url , since were doing super() , shouldnt it point to the success_url of the parent class. but why does it go to the success_url of ContactView. class ContactView(FormView): template_name = 'contact.html' form_class = ContactForm success_url = '/thanks/' def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.send_email() return super().form_valid(form) -
javascript file used in django is getting loaded with html content
html code: (my_django) [ my_lpar]# cat addlpar/templates/check.html <html><head><title>hello</title></head> <body> <div> <p> hey wassup </p> {% load staticfiles %} <script type="text/javascript" src="{% static 'js/check.js' %}"> </script> /div> </body> </html> js code: alert() When I start server, alert is not executed. So when I inspected the source of javascript file, from browser , check.js file is same as check.html: from browser: <html><head><title>hello</title></head> <body> <div> <p> hey wassup </p> <script type="text/javascript" src="/static/js/check.js"> </script> </div> </body> </html> And no obvious error is thrown in runserver: (my_django) [my_lpar]# python3.5 manage.py runserver <ip:port> Performing system checks... System check identified no issues (0 silenced). April 28, 2020 - 17:35:07 Django version 2.1, using settings 'my_lpar.settings' Starting development server at <ip:port> Quit the server with CONTROL-C. [28/Apr/2020 17:35:10] "GET /static/js/check.js HTTP/1.1" 200 168 [28/Apr/2020 17:35:11] "GET /static/js/check.js HTTP/1.1" 200 168 [28/Apr/2020 17:35:11] "GET /favicon.ico HTTP/1.1" 200 168 Please somebody help me to solve this weird issue. Why Am I not able to see javascript content.?? -
Django MySql Fulltext search works but not on tests
I used this SO question to enable full text search on a mysql db in Django application. # models.py class CaseSnapshot(BaseModel): text = models.TextField(blank=True) class Search(models.Lookup): lookup_name = "search" def as_mysql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params return f"MATCH (%s) AGAINST (%s IN BOOLEAN MODE)" % (lhs, rhs), params models.TextField.register_lookup(Search) Because Django does not support full text search on mysql, we have to add our index, so we modify the generated migration file: # Generated by Django 2.2 on 2020-04-28 03:41 from django.db import migrations, models # Table details table_name = "by_api_casesnapshot" field_name = "text" index_name = f"{table_name}_{field_name}_index" class Migration(migrations.Migration): dependencies = [("by_api", "0033_add_tag_color")] operations = [ migrations.CreateModel(...), # As auto-generated migrations.RunSQL( f"CREATE FULLTEXT INDEX {index_name} ON {table_name} ({field_name})", f"DROP INDEX {index_name} ON {table_name}", ), ] Checking the Work # dbshell mysql> SHOW INDEX FROM by_api_casesnapshot; +---------------------+--------------------------------+-------------+-----+------------+-----+ | Table | Key_name | Column_name | ... | Index_type | ... | +---------------------+--------------------------------+-------------+-----+------------+-----+ | by_api_casesnapshot | PRIMARY | id | ... | BTREE | ... | | by_api_casesnapshot | by_api_casesnapshot_text_index | text | ... | FULLTEXT | ... | +---------------------+--------------------------------+-------------+-----+------------+-----+ #shell >>> snap = CaseSnapshot.objects.create(text="XXX") # Regular query first >>> CaseSnapshot.objects.filter(text__contains="X") … -
Django Query - How to filter object to exclude a single item?
I am trying to create a blog project in which i want to show other blogs link in right side apart from the blog which i am on currently? I have tried it But i am getting an error. Here is Code def redirect(request, slug): try: exists = Blog.objects.get(title=slug) except Blog.DoesNotExist: raise Http404("Page Not Found") context = { 'content': exists, 'otherBlogs': Blog.objects.all().exclude(exists) } return render(request, "blog.html", context) I want to exclude exists from otherBlogs How can i do that? Thanks in Advance... -
Django:where should i put the admin page of my website?
Actually I'm working on a Django project.we all know to access an admin panel of the site we have the URL to access it. like this. path('admin/', admin.site.urls), Anyone can access this URL and try to attempt a log-in admin panel but I want that only super-user can access this page no anyone. How to do this. If Users of my site try to access this page does this is safe or not for my site. -
how to access Moodle REST webservice in django python
I have created a webservice which allows me to create users. But i donot know how to access it in django and how to use it. I tried following this link pypi.org/project/moodle-ws-client but it didn't get me anywhere. -
Use email created on cpanel in django
I have created an email id on my cpanel, I want to use it in django. As for gmail we write, EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_PORT = 587 EMAIL_HOST_USER = 'email@gmail.com' EMAIL_HOST_PASSWORD = 'password' What should we write for the id that has been created using cpanel. I have no idea regarding this as I am a begineer. -
Using Django SessionStore in Celery
I'm really struggling with something and have tried for days to find out what I'm doing wrong..I was thinking there might be something fundamentally wrong with what I am trying to do but I cant find anything to suggest that. I am trying to use Celery to modify a Django Session DB in the background. As a test, I have a test view which passes the sessionid to this celery task: @shared_task(name="test_celery_task") def test_celery_task(sessionid): s = SessionStore(session_key='sessionid') s['test_var'] = ["Success"] s.save() return "Task Complete" I can see the task runs, and I have added a few loggers in to check the session ID gets passed, and no error are thrown up etc. When I do this in the manage.py shell, it works fine. But I guess this is not working because it is being run by a celery worker. If it is not possible, then so be it and I'll save my time trying to work out what's wrong, but all I have read suggests that I should be able to manipulate models etc within Celery without an issue, and that a session is just another model. Am I going about this all wrong? Does anyone have any experience with … -
Save images from Form to database using ImageField Django
I am trying to save images from my Form to my database in django. All of my other CharFields seem to save from my form but not the images. When I go to admin I can upload and save images to a specified media folder and it works however, the images dont seem to save. Please help very confused, also new to this so my code may be a mess, much help is needed. Thanks [views][1] [model][2] [form][3] [urls][4] [settings][5] [1]: https://i.stack.imgur.com/ttiOz.png [2]: https://i.stack.imgur.com/EcDQQ.png [3]: https://i.stack.imgur.com/WF3YG.png [4]: https://i.stack.imgur.com/QGRzW.png [5]: https://i.stack.imgur.com/zmRxh.png -
Parent and children pagination in django
in django i have category model and post model each category has got a lot of posts so now i wanna render the tag with all its post and make pagination in there /web_dev Ex of tag name and when it takes me there i want to view all the specific tag posts and the posts might be a lot so how to add pagination using whatever weather TagDetailView(): or anything Code here : class TagDetailView(DetailView, MultipleObjectMixin): model = Tags template_name = 'one_tag.html' paginate_by = 3 def get_context_data(self, **kwargs): object_list = Posts.objects.filter(tag_belongs=self.get_object()).order_by('-id') context = super(TagDetailView, self).get_context_data(object_list=object_list, **kwargs) return context So in each tag to be viewed i wanna all its posts but with pagination feature -
IP error: fjango app not deploying with docker
I am new to Docker so I'm probably missing something obvious but here goes. I am trying to test a simple Django app with docker postgres. All I want right now is to verify that the home page is working on localhost. Debug output window gives me the following: web_1 | System check identified no issues (0 silenced). web_1 | April 28, 2020 - 17:06:23 web_1 | Django version 3.0.5, using settings 'app.settings' web_1 | Starting development server at http://0.0.0.0:8000/ web_1 | Quit the server with CONTROL-C. However when I go to 0.0.0.0:8000 I get an error that says the site can't be reached "The webpage at http://0.0.0.0:8000/ might be temporarily down or it may have moved permanently to a new web address. ERR_ADDRESS_INVALID Here is my docker-compose.yml: version: '3.7' services: web: build: . command: python /app/manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - 8000:8000 depends_on: - db db: image: "postgres:latest" ports: - "5432:5432" environment: - "POSTGRES_HOST_AUTH_METHOD=trust" Here is my dockerfile: # Pull base image FROM python:3.8 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /app # Install dependencies COPY requirements.txt requirements.txt RUN pip install -r requirements.txt # Copy project COPY . /app/ … -
unsupported operand type(s) for -: 'str' and 'datetime.datetime' - from models
I get an error in my models.py file. class TimeAnswerElement(models.Model): email = models.EmailField() costumer_time = models.DateTimeField() my_time = models.DateTimeField(auto_now_add=True) time_compartment = models.DateTimeField(blank=True, null=True) #helped function def save(self, *args, **kwargs): super().save(*args, **kwargs) TimeAnswerElement.objects.filter(pk=self.pk).update(time_compartment=self.field_compartment_function()) def field_compartment_function(self): time = self.costumer_time - self.my_time return time I am trying to subtract two fields that are correctly saved in the model through my view. Why raises my error. in my object where I use properties to override time_compartment, I don't have a string. I have correctly saved date. My views.py if request.method == 'POST' and 'save' in request.POST: form = NewTimeForm(request.POST) if form.is_valid(): cd = form.cleaned_data object = form.save(commit=False) my_date = '%s %s' %(date, cd['time']) object.costumer_time = my_date object.save() else: form = NewTimeForm() How to subtract two dates correctly by property. Do I have to use something like this for my fields? s = "2014-04-07" datetime.datetime.strptime(s, "%Y-%m-%d").date() Or is there a better way to solve this? -
Django: issue with loading static in deployment
I know this question has similar ones but nothing has been able make it for me. My static files are not loading although I feel like have followed the procedure well. I am hoping that a pair a fresh eye could spot the detail that I am missing urls.py .... if settings.DEBUG: setting.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) public_urls.py .... if settings.DEBUG: setting.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static') MEDIA_URL = '/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') STATICFILES_DIRS = [os.path.join(BASE_DIR, "staticfiles"), ] and then what is in /etc/nginx/sites-enabled/django.conf server { listen 80; server_name 35.180.131.203; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/exostocksaas/app.sock; } location /staticfiles/ { autoindex on; root /home/ubuntu/exostocksaas/inventory4/staticfiles/; } } and my errors are that the static files are not loading: GET http://35.180.131.203/css/sb-admin-2.min.css net::ERR_ABORTED 404 (Not Found) and the same for all the statics Am I missing something obvious here, I am out of things to try and any help would be welcome -
How pass a td value from html template to my views.py
Am fairly new to django, so trying to play around with django and learn at the same time by building a small project. Basically I have the below code in my html template: <tbody> {% for items in queries %} <tr> <td>{{ items.ana_user }}</td> <td class="text-center">{{ items.ana_public }}</t> <td>{{ items.ana_private }}</td> <td class="text-center">{{ items.ana_bytestx }} MB</t> <td>{{ items.ana_bytesrx }} MB</td> <td class="text-center">{{ items.ana_policy }}</t> <td>{{ items.ana_duration }}</td> <td class="btn-group"> <button class="btn btn-secondary btn-sm dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Options </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href="{% url 'stats' %}">View Live Graph</a> <a class="dropdown-item" href="{% url 'disconnect' %}">Disconnect Users</a> </div> </td> </tr> {% endfor %} </tbody> Basically by clicking any of the dropdown action. I want to take the value of the first td which is 'items.ana_user' and pass this to my views.py as a 'request.POST.get'. Your help is very much appreciated as usual. -
Can you trigger a signal upon partial update of django object via the django rest framework?
I started noticing that the patch method in django rest framework doesn't actually trigger signals, post methods seem to work fine. This is what I have: @receiver(signals.pre_save, sender=Example) def populate_time_fields_based_on_state(sender, **kwargs): example = kwargs.get('instance') if example.start_datetime is None and example.projected_end_datetime is None and example.state.label == 'Assigned': example.start_datetime = datetime.datetime.now() example.projected_end_datetime = example.created_datetime + datetime.timedelta( days=example.som_field) example.save() And I'm testing this via: client = APIClient() client.patch(f'/api/example/1/', {'state': 'Assigned'}) Is there a way to tell it to trigger the signal? Do I need to override the update method in my serializer? -
Function has no objects member pylint
I am using django 3 i am getting Function product has no object member error in this objects.all() method in my views.py file can anyone help please from django.db import models from django.shortcuts import render from django.http import HttpResponse # Create your views here. from .models import models def pro(request): pro = **product**.objects.all() return render(request , 'accounts/pro.html' , {'product' : pro}) MODELS.PY class product(models.Model): CATEGORY= ( ('InDoor' , 'InDoor'), ('OutDoor' , 'OutDoor'), ) name= models.CharField(max_length = 245 , null=True) price= models.FloatField(null = True) category= models.CharField(max_length=245 , null=True , choices = CATEGORY) description=models.CharField(max_length=500 , null= True , blank=True) date_created=models.DateTimeField(auto_now_add=True , null = True ) tags=models.ManyToManyField(tag) def __str__(self): return self.name