Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Gunicorn error : "Active: failed (Result: exit-code)"
I am trying to deploy my server inside a linode server.What i have binded gunicorn with my project,i added necessary codes inside "gunicorn.service" file.And still i am getting this error: gunicorn status (welpieenvironment) root@li2180-35:~/welpie# sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: Active: failed (Result: exit-code) since Wed 2021-02-17 13:35:00 UTC; 19s ago Main PID: 709 (code=exited, status=203/EXEC) Feb 17 13:35:00 li2180-35.members.linode.com systemd[1]: Started gunicorn daemon Feb 17 13:35:00 li2180-35.members.linode.com systemd[709]: gunicorn.service: Fai Feb 17 13:35:00 li2180-35.members.linode.com systemd[709]: gunicorn.service: Fai Feb 17 13:35:00 li2180-35.members.linode.com systemd[1]: gunicorn.service: Main Feb 17 13:35:00 li2180-35.members.linode.com systemd[1]: gunicorn.service: Faile Note:Sorry for the unfinished sentences.This is what i got from my command. Here is what i have done: binding operation (welpieenvironment) root@li2180-35:~/welpie# gunicorn --bind 0.0.0.0:8000 welpie.wsgi [2021-02-17 13:36:02 +0000] [742] [INFO] Starting gunicorn 20.0.4 [2021-02-17 13:36:02 +0000] [742] [ERROR] Connection in use: ('0.0.0.0', 8000) gunicorn.service file [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/welpie ExecStart=/root/welpie/welpieenvironment/bin/gunicorn --access-logfile - --workers 3 --bind unix:/root/welpie/welpie.sock welpie.wsgi:application [Install] WantedBy=multi-user.target Virtual Environment files Project Directory What can i do to solve this problem? -
react - create schedule (semester)
I'm new to React, I using react to build a web that retrieves data from Django, the data represents information about the courses such as day and hours, I want to display for each student his schedule for the semester in timetable (The schedule is the same for all the weeks). How do you recommend doing this? -
Some images can't be loaded, but it makes no sense
Some images can load perfectly, but some can't. The problem is, they are in the same directory, following a same naming pattern. For example, this picture can load: but this can't: I'm expecting it to be something like this: but actually, there turn out to be NOTHING. No broken-image icon, just gone, like it never existed: but when I right clicked on the image link(from the source code panel) and opened it in a new tab, the image could be shown normally: It seems like that the broswer be like: "you know what, I don't want to work for no reason. Wait, you want to see this image so eagerly? Fine, fine, I will show it..." Here is the html template: <!DOCTYPE html> <html> <body> <h1>{{ metamodel.metamodel_name }}</h1> {% for group in metamodel.group_set.all %} <h2>{{ group.group_name }}</h2> {% for product in group.product_set.all %} <a href="{% url 'exhibition:models' product.id %}"> <img src="{{ product.picture.url }}"> <p>{{ product.model }}</p> </a> {% endfor %} {% endfor %} </body> </html> The view function: def show_products(request, metamodel_id): try: context = { 'metamodel': Metamodel.objects.get(pk=metamodel_id), } except Metamodel.DoesNotExist: raise Http404("Metamodel Does NOT exist !") return render(request, 'exhibition/show_products.html', context) I'm using Firefox 85 on Windows 10. I also tried … -
How to reached joined table information? -- Django Lookups
I would like to display number of the products that are cheaper than the minimmum price of the competitor products.Also, products are need to be dynamic towards user. How can I handle it? Models: class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='products') category = models.CharField(max_length=120) brand = models.CharField(max_length=120) product = models.CharField(max_length=120) price = models.DecimalField(decimal_places=2,max_digits=100) stock = models.BooleanField() class Comp_Product(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE, related_name="comp_products") competitor = models.URLField() price = models.DecimalField(decimal_places=2,max_digits=100) change = models.FloatField() stock = models.BooleanField() last_update = models.DateField(auto_now_add=True) view: class DashboardList(ListView): template_name='dashboard_by_user.html' def get_queryset(self): return Product.objects.filter(user=self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) Products = context['object_list'] context['num_of_cheapest'] = Products.filter(price__lt=Products.annotate(Min('comp_products__price')).count() return context -
Django-Filter between two dates
Unfortunately I'm stuck and can't find a working solution yet, my Model looks like this: class SubOperatorAssignment(models.Model): operator = models.ForeignKey(Operator, on_delete=models.CASCADE) sub_operator = models.ForeignKey(SubOperator, on_delete=models.CASCADE) start_date = models.DateField(blank=False, null=False, verbose_name='Start Date') end_date = models.DateField(blank=False, null=False, verbose_name='End Date') And I would like to let the User select a Date (with the Django-Filter Library) and check in the Filter if the given Date is between the Models Start and End Date. Unfortunately Date Filter only accepts one field name and there seems to be no lookop_expr for between. Thankful for any hints on how to achieve this! -
Django redirect in views if context don´t exist
I have a template that needs one session variable to show the information. I want to configure my template in case the information don´t came to the template then redirect the user to other template. This is how my code looks now and the error that return class Feedback(TemplateView): template_name = 'cursos/pu.html' def get(self, *args, **kwargs): user_id = self.request.session.get('user_id') username = self.request.session.get('username') password = self.request.session.get('password') apiKey = self.request.session.get('apiKeyUser') complete_name = self.request.session.get('complete_name') context = super(Feedback, self).get_context_data(**kwargs) context['firstname'] = self.request.session.get('firstname') if self.request.session['quizResult'] != None: context['quizResult'] = self.request.session['quizResult'] self.request.session['quizResult'] = None self.request.session.modified = True return context else: return redirect('core:home') #feedback return context The error is: 'dict' object has no attribute 'status_code' How can I modify that to redirect to home in case self.request.session['quizResult'] == None -
django import export incrementing id field by 2
I am trying to use django-import-export in admin site and below is a snapshot of the code. But when I check in database, the id field is getting incremented by 2. Not able to understand where I am going wrong. resources.py class CountriesResource(resources.ModelResource): name = fields.Field(column_name='name', attribute= "name") countrycode = fields.Field(column_name='countrycode', attribute="countrycode") currency = fields.Field(column_name='currency', attribute="currency") currencycode = fields.Field(column_name='currencycode', attribute="currencycode") cohortcountrycode = fields.Field(column_name='cohortcountrycode', attribute="cohortcountrycode") cohortcurrencycode = fields.Field(column_name='cohortcurrencycode', attribute="cohortcurrencycode") class Meta: model= Countries exclude= 'docid','displayorder','createdon','createdby','modifiedon','modifiedby','isactive','isdeleted',) skip_unchanged = True report_skipped = False # import_id_fields = ('name',) fie lds= ('name','countrycode','currency','currencycode','cohortcountrycode','cohortcurrencycode') #admin.py class CountriesAdmin(ImportExportModelAdmin): resource_class = CountriesResource list_display = ('name', 'countrycode', 'currency', 'currencycode', 'cohortcountrycode','cohortcurrencycode') list_filter = ('name', 'countrycode', 'isactive','currencycode') search_fields = ['name', 'countrycode', 'isactive','currencycode'] #db snapshot -
How to get redirected to newly created product page with Axios POST to a route I know only after object is created (uuid route)
I'm new to React and I'm trying to create a POST with AXIOS and automatically be redirected the uuid url page of the created post but I don't know that uuid until product object is created. I'm using Django Rest as backend and I use UUIDField in my models as produit id. When I create a POST with AXIOS, a product with unknown uuid object id is created. I understand that there is maybe two solution to be redirected to the page 'object/uuid_of_object/'. Maybe there is a way to automatically GET the created product object once the POST has been made ?!? This way I would get the uuid generated by Django...and would be able to redirect to the right url. If possible I don't find anything about that on the web. (maybe I search on wrong key words). I could make a GET request to the most recent created object...maybe mixed with some caracteristics known at the moment of POST request. Not a good idea in my opinion but would maybe works. There is maybe a 3rd or more solutions but I can't manage to find one. Your help on best practice would be very appreciated. Thanks a lot … -
Add a message if the fields are empty in my Django app
So I have a Django form and what I want is that it shows a message under (like in red) each field if they are not filled. I have tried adding the "error_messages" attribute to my widgets in each field but it won't work. my forms.py: class WordForm(forms.Form): Word1 = forms.CharField(error_messages={'required': 'Please enter a word'}, required = True, label= 'Word1', widget= forms.TextInput(attrs={ 'class': "form-control is-invalid", 'placeholder': 'Enter First Word' })) Word2 = forms.CharField(error_messages={'required': 'Please enter a word'}, required = True, label= 'Word2', widget= forms.TextInput(attrs={ 'class': 'form-control is-invalid needs-validation was-validated', 'placeholder': 'Enter Second Word' })) Word3 = forms.CharField(error_messages={'required': 'Please enter a word'}, required = True, label= 'Word3', widget= forms.TextInput(attrs={ 'class': 'form-control is-invalid', 'placeholder': 'Enter Third Word' })) Result = forms.CharField(label= 'Result', required=False, widget= forms.TextInput(attrs={'class': 'form-control', 'readonly': 'True'})) my form.html: <form method="post" class="needs-validation was-validated" novalidate> {% csrf_token %} <h2>Inputs</h2> {{ form.as_p }} </form> As you can see, I have added the error messages field and also the is-invalid class in the widgets but It won't do anything. I don't really know if I have to create a function, cause I have seen those feedback messages but not with the form rendering. Help is much appreciated. -
Django : Manager isn't accessible via Process instances
I have the following models : class Process (models.Model): id = models.CharField(max_length=1000, primary_key=True) processName = models.CharField(max_length=100) class Step (models.Model): id = models.CharField(max_length=1000, primary_key=True) process = models.ForeignKey(Process, on_delete=models.CASCADE) stepName = models.CharField(max_length=100) I want to access a specific Step object. I do : step=Process.objects.get(id=stepId) When I try to access an objects in step : step.objects.all() I have the following error : AttributeError: Manager isn't accessible via Process instances How can I access objects in step? -
How do I fill a html form with fields from my database in Django and postgresql?
How do I fill a html form with fields from my database in Django and postgresql? I need to select year from drop down and value of flag(0,1,2), with the combination of these two I want my form to populate from the values stored previously in the table corresponding to the above combination. -
Issues getting primary key django
I started to learn Django and I decided to create a blog to check my skills and train myself with an actual project. In my models.py there is two models : class Article (models.Model): title = models.CharField(max_length = 100) author = models.CharField(max_length = 100) date = models.DateField(auto_now=True) content = models.TextField() is_draft = models.BooleanField(default = True) def __str__(self): return self.title class Comment(models.Model): comment_author = models.CharField(max_length = 100) comment = models.TextField() article = models.ForeignKey(Article,on_delete=models.CASCADE) def __str__(self): return self.comment_author I want to display all the title and content of every articles and the numbers of comment , to do so I used a ListView. views.py : class ArticleListView (ListView): context_object_name = 'articles' model = models.Article # print(models.Article.objects.get(pk=1).models.Comment_set.all()) def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['title'] = models.Comment.objects.get(pk=1) # I don't know how to change this value context['id'] = self.model.id return context article_list.html : {% for article in articles %} <h2>{{ article.title }}</h2> <p>{{ article.content }}</p> <h5>Id of article is {{ id }}</h5> <h6>{{ title }}</h6> {% endfor %} I wanted to use count() on Comment so I get the numbers of comments by post. To get the list of article's comments I thought that I need the pk for each article so I can find … -
django , unable to upload file to a directory using filefield ,
am new to django . and am really confused right now . So i have a code which should upload a file to UPLOAD directory . from their it will be used for furthur processing . But currently am not able to push the file in filefield to UPLOAD directory I did a deep search but was not able to find any related solution to this . so below is my code : class Files(models.Model): files_to_upload = models.FileField(upload_to='UPLOAD/', default = None, validators=[validate_file]) path = models.CharField(max_length=100) server = MultiSelectField(choices=server_list) snippet = models.ForeignKey(Snippet, related_name = "files", on_delete=models.CASCADE) def __str__(self): return str(self.snippet) class Meta: db_table = "files" and in files.html: .<form enctype="multipart/form-data" action="{% url 'files' %}" method="POST"> i gave this too as instructed by one stack question answer . Is there any other thing i should check -
Django Admin: Values for not displayed fields
I need to manually add an entry to the database via the admin panel but give the entry some initial values: #models.py class Product(models.Model): price = models.DecimalField("price") status = models.PositiveIntegerField("status") name = models.CharField("name", max_length=31, unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE,) #admin.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = ["price", "name",] @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ["price", "status", "name",] list_filter = ["status",] form = ProductForm readonly_fields = ["status", "user",] Admin should be able to create a Product and give it a name and price, but the status value should be set to "manually created". I already tried this approach and this one, but did not find a solution. What is the correct way to set the status and user so that the form validates? I am not able to avoid sqlite3.IntegrityError: NOT NULL constraint failed: _TEST_Product.status using the linked posts. -
Send Emails to every user based on their notification's settings
I want to schedule Emails to be sent based on user's settings for example user would have some options like no notifications once daily at 8am twice daily at 8am and 4pm so how should i implement this based on each user's preference using cronjobs? -
Many-to-many relationship as JSON
Suppose I have have a model consisting of facilities that have employees which work on certain days of the week. #models.py class Weekday: name = models.CharField() # 'Monday', 'Tuesday', etc. class Facility: name = models.CharField() class Employee: name = models.CharField() employer = models.ForeignKey(Facility) # e.g. works on Mondays and Tuesdays weekdays = models.ManyToManyField(Weekday) Now I want my TemplateView to generate a JSON that lists the employees of a given facility by the days of the week. This needs to be JSON because a weekly calendar shall be rendered by javascript. # views.py class CareFacility(DetailView): model = Facility def get_context_data(self): return { 'week_plan_json': ? } The JSON may be something like: [ { 'model': 'Weekday', 'name': 'Monday', 'employees': [ { 'model': 'Employee', 'name': 'John' }, { 'model': 'Employee', 'name': 'Ida' } ] }, { 'model': 'Weekday', 'name': 'Tuesday', 'employees': [ { 'model': 'Employee', 'name': 'John' } ] }, { # Wednesday # etc... } ] The exact format may be different, but I am wondering how to combine the three models in a way that they are grouped by Weekday -
How to pass " # " in url of django site
I have site with django as backened , and i have a url pattern like this in mu urls.py path('api/getnews/home/post/<str:titleInUrl>', getnews.getSpecificHomeNews , name='getspecificHomenews') , Now when I pass Normal Strings in my url like this , things go well api/getnews/home/post/Petrol,%20diesel%20prices%20are%20rising%20but%20why%20govt%20does%20not%20look%20worried But , When i pass anything with '#' symbol in it , Python make it a comment api/getnews/home/post/#MeToo:%20What%20Priya%20Ramani%20said%20after%20acquittal%20in%20MJ%20Akbar%20defamation%20case and I am not able to get my string after the # symbol Anyone Knows , How to get rid of it Thanks in Advance -
there is an error in django-summernote image. I don't know why
enter code here from django_summernote.widgets import SummernoteWidget ,SummernoteInplaceWidget class PostForm(forms.ModelForm): content = forms.CharField(widget=SummernoteWidget( attrs={ 'iframe':False, 'attachment_filesize_limit': 10 * 1024 * 1024, 'summernote': {'width': '100%', 'height': '450px'} })) class Meta: model = Post fields = ('title','hook_text','content','head_image','category') enter image description here enter image description here When I post with big size picture. the image is always have absolute size. It doesn't reduce the size following the browser size. -
Site cannot be reached with Nginx ,Gunicorn , django on aws ec2
I have followed this tutorial https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 to setup my django app on ec2 but it is not accessible. When I hit the url it says that site cannot be reached. I did ssh to my ec2 instance and uses the curl command it shows me the html page but withot it says connection cannot be established.enter image description here -
request.FILES is always empty
When I try to post a Django form containing a file field, the file field is being passed as part of the request.POST rather than request.FILES (which is empty). This throws a MultiValueDictKeyError on submitting the form. Form html <form class="form-horizontal" action="{% url 'drinkConf' %}" method="post" enctype="multipart/form-data" > {% csrf_token %} <!-- Text input--> <label class="col-md-4 control-label" for="date">Date</label> <div class="col-md-4"> <input id="date" name="date" type="text" placeholder="" class="form-control input-md" required=""> </div> <!-- Textarea --> <label class="col-md-4 control-label" for="notes">Notes</label> <div class="col-md-4"> <textarea class="form-control" id="notes" name="notes"></textarea> </div> <!-- Multiple Radios (inline) --> <label class="col-md-4 control-label" for="rating">Rating</label> <div class="col-md-4"> <label class="radio-inline" for="rating-0"> <input type="radio" name="rating" id="rating-0" value=1 checked="checked"> 1 </label> <label class="radio-inline" for="rating-1"> <input type="radio" name="rating" id="rating-1" value=2> 2 </label> <label class="radio-inline" for="rating-2"> <input type="radio" name="rating" id="rating-2" value=3> 3 </label> <label class="radio-inline" for="rating-3"> <input type="radio" name="rating" id="rating-3" value=4> 4 </label> <label class="radio-inline" for="rating-4"> <input type="radio" name="rating" id="rating-4" value=5> 5 </label> </div> <label class="form-label" for="image">Upload an image</label> <input type="file" class="form-control" id="image" name="image" /> <!-- Button (Double) --> <label class="col-md-4 control-label" for="Submit"></label> <div class="col-md-8"> <input class="btn btn-success" type="submit" value="Submit" /> <button id="Cancel" name="Cancel" class="btn btn-inverse">Cancel</button> </div> </div> </form> My view @login_required def DrinkBeerConfirm(request): if request.method == 'POST': if request.POST['date']: cellar_id = request.session['cellar'] #Get cellar record ID cellarEntry … -
Heroku deploy failed: Couldn't import Django. Are you sure it's installed?
I am trying to deploy my Python app to Heroku. I am using pipenv. I have defined Pipfile: ... [packages] django = "*" ... I defined Procfile: release: python manage.py migrate web: gunicorn scrapper.wsgi clock: python scrapper/scheduler.py I also added config variable for settings: DJANGO_SETTINGS_MODULE: scrapper.settings When i push my changes to Heroku, deply fails with the following error: File "manage.py", line 17, in "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
django cripsy form installed failed
My django Version >> 3.1.6 Python version >> 3.8.6 Error >> while installing in virtual env pipenv install django-cripsy-forms Could not find a version that satisfies the requirement django-cripsy-forms ERROR: No matching distribution found for django-cripsy-forms I am new in django please which version of django|python i have to insall -
django get values from datetimefield
class Transaction(models.Model): start = models.DateTimeField(default=timezone.now) I've a model like this. I want to extract date, year from start variable. When I try start.year(), I'm seeing this error Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'DateTimeField' object has no attribute 'year'``` -
How to check if the cookie exist or not and allow the authority to the particular page on the basis of it?
I am creating an authorisation with custom middleware in Django where I save the token in cookie, now I want to check if the cookie is valid or not if it's valid then allow the user to access the page or else should redirect to login page. this is my login method in views.py where I get the token and set it to cookie def loginPage(request): form = AuthenticationForm() if request.method == 'POST': print("login........") username = request.POST.get('username') password = request.POST.get('password') bearerTokenResponse = requests.post( 'http://localhost:8000/auth/login', json={"email": username, "password": password}) print(bearerTokenResponse) code = bearerTokenResponse.json()['code'] # Check if the code is 200 it's successfully get the token if code == 200: token = bearerTokenResponse.json()['token'] print(token) response = HttpResponse("Cookie Set") # Render the home page(patients) response = render(request, 'dashboard.html') # Set the cookie with key name 'core-api' response.set_cookie('core-api', token, max_age=3600) # expire in 1 hour return response return render(request, 'login.html', {'form': form}) # Get the cookie with the key name 'core-api' def getcookie(request): s = request.COOKIES['core-api'] return HttpResponse(s) and the middleware from django.conf import settings class LoginMiddleware: def __init__(self, get_response): #print(get_response) pass def __call__(self, request): #response = self.get_response(request) pass #return response def process_view(self, request, view_func, *view_args, **view_kargs): pass def process_exception(self, request, exception): pass def … -
How to use filters on Foreignkey Fields in Django Rest Framework
In the below class 'dep' is a Foreign Key field associated with Employee model. Views.py class Sample(ListAPIView) queryset=Employee.Objects.all() serializer_class = EmployeeSerializer filter_backends = [SearchFilter] search_fields = ['dep'] Models.py class Employee(models.Model): FirstName=models.CharField(max_length=30) LastName = models.CharField(max_length=30) Salary = models.FloatField() Email = models.CharField(max_length=35) Dep =models.Foreignkey(Department) but when I pass dep has a filter to the endpt , it throws Related Field got invalid lookup: icontains Error.