Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mac terminal: For Visual Studio Code, Django how to activate virtualenv without having to go into the folder
I have a bit of a messy set up and I'm trying to find an easier way to activate my virtualenv without having to navigate into the folder, whilst using terminal. Currently my virtualenv bin file is in: Desktop/Projects/test/ In order to activate my virtualenv I have to go into this file via terminal and then type: source bin/activate then cd . . and work my way back to: Desktop/Projects/challenge/task/ which is where the manage.py file is kept and where I work on the project. I have seen on Windows you can use bash and while, for example, in: Desktop/Projects/challenge/task/ you can type: workon test and that should activate the vitualenv (test), but this command doesn't seem to be working in terminal on Mac. Is there a Mac version of this command? So I don't have to be hopping in and out of folders to a) activate the virtualenv and b)then get to the main project folder. I'm new to this so any additional advice would also be much appreciated. -
Recieved an error while running python manage.py migrate and python manage.py runserver
form.py This is my form tab. from django.contrib.auth.models import User from security_app.models import UserProfileInfo from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('Username','email','password') class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('portfolio_site','profile_pic') models.py This is my models tab from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank=True) def __str__(self): return self.user.username urls.py This is my urls tab under my app "security_app" from django.conf.urls import url from security_app import views app_name = 'security_app' urlpatterns = [ url(r'^register/$',views.register,name='register') ] view.py This is view tab. from django.shortcuts import render from security_app.forms import UserForm, UserProfileInfoForm # Create your views here. def index(request): return render(request,'security_app/index.html') def register(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True else: print(user_form.errors,profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request,'security_app/registration.html', {'user_form':user_form, 'profile_form':profile_form, 'registered':registered}) base.html This is my base tab from which i inherit nav bar to other htmls tab <!DOCTYPE html> <html> <head> <meta … -
Subtract two DateTime fields in Django
How can I subtract two different formats for DateTime field to get the difference of days and time between them. My models: class TimeAnswerElement(models.Model): costumer_time = models.DateTimeField() my_time = models.DateTimeField(auto_now_add=True) time_compartment = models.DateTimeField(blank=True, null=True) My views: object = get_object_or_404(TimeAnswerElement, id=1) time_compartment = object.my_time - object.costumer_time #My data for fields #object.my_time = 2020-04-28 19:31:35.550655+00:00 #object.costumer_time = 2020-04-28 11:11:00 My solution returns an error: unsupported operand type(s) for -: 'datetime.datetime' and 'str' -
how to request data with the earliest date
trying to get the earliest date based on all the pins in the database but it would return a data with the date of value null. the date field is optional for the user. Trying to figure out a way to get the earliest date without returning one with null class MinPinDate(viewsets.ModelViewSet): queryset = pin.objects.all().order_by("Date").reverse()[:1] serializer_class = PinSerializer router = routers.DefaultRouter() router.register('api/minPinDate', MinPinDate, 'pin') urlpatterns = router.urls -
Inline form factory does not load all documents after POST in Django
I need some help with inline formset in Django. I am using the inline form set factory to upload documents to Document model which has foreign key reference to Department Table as follow: model.py: class Department(models.Model): DepId = models.AutoField(primary_key=True) Name = models.CharField(max_length=100) ShortName = models.CharField (max_length=25) def __str__(self): return (str(self.DepId) + " "+ self.ShortName+ " is created!") class Meta: db_table = 'Department' # Table Name managed = True verbose_name = 'Departments' # Verbose Name of Table. class Document(models.Model): CATEGORY = (('Type1', 'Report Type 1'), ('Type2', 'Report Type 2'),) Id = models.AutoField(primary_key=True) Name = models.CharField(max_length=300) DocType = models.CharField(max_length=300, choices=CATEGORY) DocContent = models.FileField(upload_to='reports/') DepId = models.ForeignKey(Department, on_delete=models.CASCADE, db_column="DepId") UploadedDate = models.DateField(default=timezone.now, null=True) def __str__(self): return (str(self.Name)) class Meta: db_table = 'Document' managed = True verbose_name = 'Document' def delete(self, *args, **kwargs): self.DocContent.delete() super().delete(*args, **kwargs) view.py def doc_loading_view(request, pk, *args, **kwargs): DocumentFormSet = inlineformset_factory(Location, Document, fields=('Name', 'DocContent', 'DocType',), extra=1) department = Department.objects.get(DepId=pk) formset = DocumentFormSet(queryset=Document.objects.none(), instance=department) context = { 'department': department, 'form': formset, } if request.method == "POST": formset = PaymentDocumentFormSet(request.POST, request.FILES, instance=location) if formset.is_valid(): for form in formset: fileform = form.save(commit=False) print (fileform.Name) return redirect('getdoc', pk=department.DepId) else: messages.info(request, "Errors in Formset: "+formset.errors) return render(request, "getdoc", context) Template: {% extends 'base.html' %} {% … -
Prevent audio player from page refresh?
im working on a audio player page on Django. I have a bottom audio player and I have 4 pages in Navbar. When I change the page player stops. I want the player keep playing all the time. Please I need help guys. -
generating unique id in django
my models.py : class clients(models.Model): client_id = models.CharField(max_length=8,unique=True, null=False, blank=True,primary_key=True) client_identity_id = models.IntegerField(unique=True, null=False, blank=False) ' ' my serializer.py : class UserSerializer(serializers.ModelSerializer): class Meta: model = clients fields = ('client_identity_id','client_id','client_firstname','client_middlename','client_lastname','client_country','money','client_num') read_only_fields = ('money',) def create(self, validated_data, **kwargs): validated_data['client_id'] = ''.join(secrets.choice(string.ascii_uppercase + string.digits) for i in range(8)) return clients.objects.create(**validated_data) my views.py : def post(self,request): data=request.data serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) when i make a post request it should make a unique client_id for the user , but it keep it Null , i tried too many ways to generate unique id , but no one of them did work ,please help me with making edit on my code to make it work (do not just tell me "do that and that") , and thanks -
I can't run a python file in a subfolder of a Django Project
import urllib.request, requests, time, random, datetime from os.path import basename from bs4 import BeautifulSoup from makale.models import Yazar, Makale, Gazete from django.shortcuts import render, redirect Views of makale App stored within gazete_views folder. I have imported above mentioned models and run the script by following command: python makale/gazete_views/birgun.py But above command reaches following error: Traceback (most recent call last): File "makale/gazete_views/birgun.py", line 4, in <module> from makale.models import Yazar, Makale, Gazete Below is __init__.py file located in gazete_views folder from .haberturk import * from .yenisafak import * from .sozcu import * from .birgun import * from .hurriyet import * from .turkiye import * from .artigercek import * from .dunya import * from .aksam import * __init__.py file located in makale App is empty. I need to run these views located in gazete_views folder. Because I need to run all of them with a cron job. -
How to retain selected option after submitting a form Django
I have a select tag with elements loaded from a DB. When I submit the form (search), I want to retain the selected value and show it in an . I am not using ajax and any django forms. I am just using plain html select tags inside form tag. My view is something like: def filter(request): qs = StrategicObjective.objects.all() strategicplans = StrategicPlan.objects.all() strategicplan = request.GET.get('strategicplan') if strategicplan != 'Choose...': qs = qs.filter(strategicplan__id=strategicplan) else: qs = [] return qs def HomeView(request): qs = filter(request) context = { 'queryset': qs, 'strategicplans': StrategicPlan.objects.all(), } return render(request, "home.html", context) My template: <div id="stratplan_search" class="container"> <form class="form-inline" method="GET"> <label class="my-1 mr-2" for="strategicplan">Strategic Plan</label> <select class="custom-select my-1 mr-sm-2" id="strategicplan" name="strategicplan"> <option selected>Choose...</option> {% for stratplan in strategicplans %} <option value="{{ stratplan.id }}">{{ stratplan }}</option> {% endfor %} </select> <button type="submit" class="btn btn-primary my-1">Submit</button> </form> </div> I would like to show the selected option inside an : <h1> {% for strategicplan in strategicplans %} {{strategicplan}} {% endfor %} </h1> Any help would be appreciated. The preference in simple terms because I am a Beginner in development. -
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.