Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
guys help me cant fix it i have tried many tutorials but they dont work like they showed
my json setting is c:/Users/user/Desktop/hellodjango/myenv4/Scripts/python.exe but when i try to run python manage.py runserver the error is(myenv4) C:\Users\user\Desktop\hellodjango\web_project\src>python manage.py runserver C:\python\Python37-32\python.exe: can't open file 'manage.py': [error] No such file or directory though my path for virtual environment is c:/Users/user/Desktop/hellodjango/myenv4/Scripts/python.exe i have properly installed the django why does this happenenter image description here this is my file -
Django Multiple Forms from differents models
i m quite new with Django but i m stuck since a day on a problem that i can t solve. I have to create forms with a lot of fields. The fields comes from different models and i want to save them all at once. I want to display it with a slick so the user experience will be better and not overwhelmed by the amout of fields to fill. The slick part is not a problem. My problem is to render multiple form separated in different div on the same page. In this i want to display the candidateDetails form not only the candidate one. here my actual code for only one form that is working. The forms : class CandidateApplicationForm(ModelForm): position = forms.ChoiceField(choices=POSITION, widget=forms.RadioSelect) class Meta: model = Candidate fields = ['firstName', 'lastName', 'mailAddress', 'address', 'city', 'country', 'nationality', 'position', ] widgets = { 'firstName': forms.TextInput(attrs={'class': 'input'}), 'lastName': forms.TextInput(attrs={'class': 'input'}), 'address': forms.TextInput(attrs={'class': 'input'}), 'city': forms.TextInput(attrs={'class': 'input'}), 'nationality': forms.TextInput(attrs={'class': 'input'}), 'Type of programme': forms.TextInput(attrs={'class': 'input'}), } class CandidateDetailsForm(ModelForm): class Meta: model = CandidatesDetail fields = ['birthPlace', 'birthDate', 'nationality', ] The Views : class RegisterCandidate: def __init__(self): self.method = None def candidateapply(request): apply = candidateregistrationform.CandidateApplicationForm() if request.method == 'POST': form_candidate … -
What do these arguments mean in swagger_auto_schema (Django)?
The project uses a swagger. There is the following code. @swagger_auto_schema( manual_parameters=[ Parameter('download', IN_QUERY, 'Set `Content-Disposition=attachment` to make browser to download file' 'instead of showing it.', type='bool'), Parameter('share_id', IN_PATH, type='uuid') ], security=[], responses={'400': 'Validation Error (e.g. base64 is wrong)', '200': VideoSerializer} ) Please explain what each argument is responsible for. I read the documentation, but understood little ... Particularly interested in '200': VideoSerializer -
ProgrammingError: 1064 while executing inspectdb with django and mysql database
I have two databases configured in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '5432', }, 'db2': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'database', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'ip address', 'PORT': 'port', } } The server which hosts db2 uses mysql 4.1.2. I am using Python 3.7.3 + django 2.2.5 + mysqlclient 1.4.4. When I run python manage.py inspectdb --database db2 I get the following error: django.db.utils.ProgrammingError: (1064, "You have an error in your SQL >syntax; check the manual that corresponds to your MySQL server version for >the right syntax to use near 'TABLES' at line 1") I have printed the 'query' and it is: SHOW FULL TABLES I have tried to manually connect to the database (MySQLdb.connect + cursor) and retrieve data from a table and it worked fine. My problem is basically the same as (Error 1064 Django inspectdb), but that guy didn't get any help. Hopefully I will. What I am trying to accomplish is use data from db2 as foreign keys in the default. For example, I have some items described in the default database and some persons defined in db2. I would like to associate a person … -
Heroku aggregate metrics from JSON logs
I have a Django application running on Heroku with json logs outputted to papertrail in the following format (examples): {"message_type":"profile", "method":"a", "runtime":1000, "timestamp: 1570524933} {"message_type":"profile", "method":"b", "runtime":1020, "timestamp: 1570524934} {"message_type":"profile", "method":"a", "runtime":2020, "timestamp: 1570524934} For instance, I want to construct a chart on Grafana that can show the mean runtime of methods a and b across the day but am unsure as to how I can run select or run aggregation functions such as (mean, max, min, etc.) using data from papertrail. So far I have looked at setting up an alert on papertrail for certain log criteria that will then ping Graphite Grafana, however this only gives the summed number of events. Does anyone have any input on this can be achieved? -
how can i use ckeditor feature Real-time collaborative in django
can i use ckeditor feature Real-time collaborative in django ? ckeditor Documentaion Link here -
How To Provide A Class To Fields In A Django Template?
I was working a project on mine, in which I needed to provide a class to a field in form which is a input box, but don't know how to do so. My Template: {% extends 'diary/base.html' %} {% block title %}Register{% endblock title %} {% block content %} {% load staticfiles %} <link rel= "stylesheet" type= "text/css" href = "{% static 'users/register.css' %}"> <div id="login-box"> <div class="left-box"> <h1>Register</h1> <form action="{% url 'register' %}" method="post"> {% csrf_token %} {% for non_field_error in form.non_field_errors %} <p>{{ non_field_error }}</p> {% endfor %} {% for field in form %} {{ field }} {% for error in field.errors %} <p>{{ error }}</p> {% endfor %} {% endfor %} <input type="submit" value="SIGN UP" name="signup-button" class="signup-btn"> </form> </div> <div class="right-box"> </div> </div> {% endblock content %} In this specific part: {% for field in form %} {{ field }} {% for error in field.errors %} I want to provide a class to {{ field }}. I tried this: {{ field(class="txtb") }} This is how I use to provide a class in Flask, but in Django this didn't worked. Any Help Would Be Appreciated! -
Django Storages: use 2 media sources
In my Django APP I use Dropbox API for media files. This are the settings. MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DROPBOX_OAUTH2_TOKEN = 'my_token' DROPBOX_ROOT_PATH = '/my_app/' I want to ADD another storage in Google CDN, keeping Dropbox. Is it possible? Should be something like overriding the DEFAULT_FILE_STORAGE? MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") DEFAULT_DROPBOX_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DROPBOX_OAUTH2_TOKEN = 'my_token' DROPBOX_ROOT_PATH = '/my_app/' MEDIA_URL = '/media_2/' MEDIA_ROOT = os.path.join(BASE_DIR, "media_2") DEFAULT_DROPBOX_STORAGE = 'storages.backends.google.GoogleStorage' GOOGLE_OAUTH2_TOKEN = 'my_token' DROPBOX_ROOT_PATH = '/my_app/' I couldn´t find much info about this dual Django Storages use. Any advice welcome! -
Using celery worker in Heroku causes timeout
I'm using Heroku for my Django project which runs on the daphne server. And also I have a celery worker to run tasks parallelly to reduce response time. Below is my Procfile web: daphne myproject.asgi:application --port $PORT --bind 0.0.0.0 -v 0 worker: celery worker -A myproject --loglevel=debug --concurrency=8 Scenario: I need to generate a statement using the last 24 months of balance data. For that, I have two endpoints GET BALANCE - Fetch the 24 months of balance ( each month is considered as a task and 24 tasks are run using celery worker ) GENERATE STATEMENT - Generate the statement for 24 months of data ( This API is called immediately after GET BALANCE API ) If I test for a single company it takes 15 - 20 seconds for the first API. But if I test for 2 or more companies (using load testing) it first company alone passes and others are failed due to HEROKU 30 Seconds Timeout problem For example for 5 companies: C1 - takes 15 seconds to complete - Pass C2 - takes 27 seconds to complete - Pass C3 - takes 43 seconds to complete - Timeout C4 - takes 48 seconds to … -
CRUD table / view not refreshing after form save
Django App Refresh Issue After submitting form for updating/deleting/creating items, view (CRUD table) does not refresh. The problem started after i have added the filtering of the model Here are the relevant code pieces: views.py: def item_list(request):`enter code here` user_list = item.objects.all() user_filter = UserFilter(request.GET, queryset=user_list) return render(request, 'items/item_list.html', {'filter': user_filter}) def search(request): user_list = item.objects.all() user_filter = UserFilter(request.GET, queryset=user_list) return render(request, 'items/item_list.html', {'filter': user_filter}) def save_item_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() print('x') data['form_is_valid'] = True user_list = item.objects.all() user_filter = UserFilter(request.GET, queryset=user_list) data['html_item_list'] = render_to_string('items/includes/partial_item_list.html', {'filter': user_filter}) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def item_create(request): if request.method == 'POST': form = itemform(request.POST) else: form = itemform() return save_item_form(request, form, 'items/includes/partial_item_create.html') def item_update(request, pk): Item = get_object_or_404(item, pk=pk) if request.method == 'POST': print('postx') form = itemform(request.POST, instance=Item) else: form = itemform(instance=Item) print('postitem') return save_item_form(request, form, 'items/includes/partial_item_update. Once adding a new item in the model it should also refresh the view. -
Accessing request.body and request.FILES from mailgun forwarding route
My goal is to read the contents of a forwarded mail with an attachment using mailgun's route. When the email doesnt include an attachment, i can freely grab other attributes like the sender,subject and text but when i try to access request.FILES i get error saying You cannot access body after reading from request's data stream even though i have added @csrf_exempt decorator to my view function data =urllib.parse.parse_qs(raw_request_body.decode()) subject = data['subject'] sender = data['sender'] date = data['Date'] text = data['stripped-text'] but when i try to even get request.FILES after this block of code, it throws an error -
Reverse for 'user-posts' with arguments '('',)' not found
i got this Exception : Reverse for 'user-posts' with arguments '('',)' not found. 2 pattern(s) tried: ['user/(?P[^/]+)(?P\.[a-z0-9]+/?)$', 'user/(?P[^/]+)$'] and i don't know what is the problem here is my urls.py urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts') and this is my home {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> why do i get this Exception ? -
502 Bad gateway nginx with gunicorn & django
I'm deploying django project using gunicorn and nginx. My nginx setting is, server { listen 8000; server_name 0.0.0.0; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/gagan/saporawebapp; } location / { include proxy_params; proxy_pass http://unix:/home/gagan/saporawebapp/saporawebapp.sock; } } when i run sudo nginx -t It shows that setup is correct . Then i started gunicorn using gunicorn --daemon --workers 3 --bind unix:/home/gagan/saporawebapp/saporawebapp.sock saporawebapp.wsgi Then nginx is showing 502 bad gateway. Corresponding error log is, 2019/10/08 07:51:34 [emerg] 3988#3988: open() "/etc/nginx/sites-enabled/saporawebapp" failed (2: No such file or directory) in /etc/nginx/nginx.conf:62 2019/10/08 07:59:54 [crit] 4278#4278: *1 connect() to unix:/home/ubuntu/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 42.108.169.252, server: 0.0.0.0, request: "GET /signup/ HTTP/1.1", upstream: "http://unix:/home/ubuntu/myproject/myproject.sock:/signup/", host: "157.245.108.160:8000" 2019/10/08 08:05:19 [crit] 4278#4278: *5 connect() to unix:/home/ubuntu/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 42.108.169.252, server: 0.0.0.0, request: "GET /signup/ HTTP/1.1", upstream: "http://unix:/home/ubuntu/myproject/myproject.sock:/signup/", host: "157.245.108.160:8000" 2019/10/08 08:06:24 [crit] 4744#4744: *1 connect() to unix:/home/ubuntu/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 42.108.169.252, server: 0.0.0.0, request: "GET /signup/ HTTP/1.1", upstream: "http://unix:/home/ubuntu/myproject/myproject.sock:/signup/", host: "157.245.108.160:8000" 2019/10/08 08:14:47 [alert] 5279#5279: 768 worker_connections are not enough 2019/10/08 08:14:47 [error] 5279#5279: *763 … -
how to seperate the each image individual?
'UploadSliderImage': [<InMemoryUploadedFile: squash-40790_640.png (image/png)>, <InMemoryUploadedFile: iconfinder_document_image_add_103475.png (image/png)>, <InMemoryUploadedFile: human_ubuntu-wallpaper-1600x900.jpg (image/jpeg)>] I need a = squash-40790_640.png,iconfinder_document_image_add_103475.png,human_ubuntu-wallpaper-1600x900.jpg Because I need to store the multiple images in single row one column like id | Images | 1 | squash-40790_640.png,iconfinder_document_image_add_103475.png,human_ubuntu-wallpaper- | | 1600x900.jpg | -
Javascript nested quotes with django tags
Hi i know this question get asked alot but i haven't found any answer related to Django tag and i have tried alot of method using ' in \" in " but no result, i still got console format error for my javascript My current line of code: <button type="button" class="btn btn-icon icon-left btn-info" onclick="location.href='{% url 'search_filter_by_id' filter_id=filter.id %}'"><i class="fas fa-search"></i>Search</button> The problem is the 'search_filter_by_id' cause escape quotes problem for me And i can't put it in a separate script tags due to filter.id only show on the line (for loop to output data each line) The django tag: {% url 'search_filter_by_id' filter_id=filter.id %} will output a url string but it required 'search_filter_by_id' to be in a quote for the tag to output the url string. Any help would be appreciate :D! -
Setting header name in list_filter when referencing foreign key in Django
I have a ProductType and Transaction model. The Transaction model references ProductType using a foreign key. I use list_filter to filter on ProductType in the admin environment for the Transaction model. However, the header name in the list filter is correct, since it calls the filter option "By name" instead of "By product type". How can I update this header name to "By product type"? models.py class ProductType(models.Model): name = models.CharField(max_length=20) class Transaction(models.Model): product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE) admin.py @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): list_filter = ['product_type__name'] -
How to filter an existing queryset by the month instead of day
I have a queryset that displays the amount of followers for each day of the month. Views: context["brandtwitterFollowerCounts"] = ( TwitterFollowerCount.objects.filter( twitter_account=self.object.twitter_account, followers__gt=0 ) .distinct("created__date") .order_by("created__date") ) context["brandTwitterFollowCreated"] = [ i.created.strftime("%d %m") for i in context["brandtwitterFollowerCounts"] ] context["brandTwitterFollowers"] = [ i.followers for i in context["brandtwitterFollowerCounts"] Dataset: var newDataObjectTwo = { labels: {{ brandTwitterFollowCreated|safe }}, datasets: [{ label: 'Daily', backgroundColor: 'rgb(255, 255, 255)', fill: false, borderColor: 'rgb(29, 161, 242)', data: {{ brandTwitterFollowers|safe }} }], } I would like to filter this by months instead now. So as there are currently 3 months (08, 09, 10), the graph should only show 3 data points. Sorry if this doesn't make sense, I am not sure what the best way to explain it is. -
django - How to upload file to the folder in filefield
i am saving a form with a filefield, and saying upload_to to a user_path from the userprofile. I do not know how to write the view for the form models.py def nice_user_folder_upload(instance, filename): extension = filename.split(".")[-1] return ( f"{instance.UserProfile.Assigned_Group}/{filename}" ) class Metadataform(models.Model): id = models.AutoField(primary_key=True) Authors_Name = models.CharField(max_length=500, blank=True, null=True) Document = models.FileField(upload_to=nice_user_folder_upload) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Assigned_Group= models.CharField(max_length=500, choices=Group_choices, default='Please Select') def __str__(self): return self.user.username views.py def Metadata_submission(request): Authors_Name = request.POST["Authors_Name"] if request.method == 'POST': form = Fileuploadform(request.POST, request.FILES) if form.is_valid(): form.save() return render(request, "home.html") else: form = Fileuploadform() i am getting an AttributeError at /Metadata_submission/ 'Metadataform' object has no attribute 'UserProfile' -
How could django's save() method of model know where to save among db tables?
Save() function must know where to save data, especially the exact table. Assume that there exist Question model and I create a new record and save it through q.save() like below. Although I haven't give the information of table actually, but it works well. I want to know how save() method can know the table name needed. def create_question(request, question): q = Question(question_text=question, pub_date=timezone.now())pub_date=timezone.now()) q.save() -
How to do validation in django serializers?
I have 2 custom validation functions created using packages from PyPI, I want to inlcude them in my serializers.py in my django project before converting it to JSON using rest. Problem is i dont know where or how to put the functions in such that the code will run through it. Here is my code: /* serializers.py */ import re import phonenumbers from rest_framework import serializers from phonenumbers import carrier from validate_email import validate_email class basicSerializer(serializers.Serializer): emailplus = serializers.EmailField() country = serializers.CharField(max_length=2) phone_number = serializers.CharField(max_length=100) def validate_emailplus(self): email = self.validated_data.get("email") if not validate_email(email, check_mx=True, verify=True): raise serializers.ValidationError("Invalid email") return email /* views.py */ from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import basic from .serializers import basicSerializer class basicList(APIView): def get(self, request): basic1 = basic.objects.all() serializer = basicSerializer(basic1, many=True) return Response(serializer.data) def post(self): pass As you can see I am not using models.py anymore and serializers.py as some sort of model with the given email and phone fields. In order for my function to work (which is not at the moment), it needs to use get() method from the entered data and … -
SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted in django production?
I've a djagno app deployed on heroku. In one of the section i'm sending email to the user using smtp gmail settings. The emails are sent successfully when I run project locally but not on my same deployed project on heroku. I've seen many of the other answers on stackoerflow but none of them resolves my issue. I've enabled the 2FA on my google account and generated an APP password and using that password in my settings file. Turning on allow_less_secure_app option isn't suggested by other developers My settings.py file email settings- EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER2') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS2') My views.py view handling the mail- def index(request) if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): message = form.cleaned_data['message'] email = form.cleaned_data['email'] subject = "You got a message" thoughts = "{} by {}".format(message,email) recipients = ['xyz@gmail.com'] sender = 'abc@gmail.com' send_mail(subject, thoughts, sender ,recipients,fail_silently=False) return HttpResponse() else: form = MyForm() return render(request,'my_webapp/index.html',{'form':form}) The error I'm getting in heroku logs is- raise SMTPAuthenticationError(code, resp) 2019-10-07T18:22:12.174365+00:00 app[web.1]: smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials w2sm9789664qtc.59 - gsmtp') -
how to fix "running scripts is disabled on this system" in vs code, i am using django2
i am trying to run server but its aint working and i can neither able to activate virtualenv.. winter\scripts\activate : File G:\enna\winter\scripts\activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1 + winter\scripts\activate + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess -
User logout by session in Django Rest Framework
I have a application, where frontend written by Angular 6 and backend - by Django Rest Framework. User logging out implemented on the frond whith following code: @Component({ selector: 'app-logout-modal', templateUrl: './logout-modal.component.html', styleUrls: ['./logout-modal.component.scss'] }) export class LogoutModalComponent implements OnInit { constructor(public thisDialogRef: MatDialogRef<LogoutModalComponent>, private router: Router, @Inject(MAT_DIALOG_DATA) public data: any) { } ngOnInit() { } logoutAndClose(): void { localStorage.clear(); this.thisDialogRef.close(); this.router.navigateByUrl(RouteUrls.Login); } } class ProfileSettingsViewset(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): @action(detail=False, methods=['post']) def logout(self, request): #??? return Response(status=status.HTTP_200_OK) That is, the user is not actually logging out. How can to implemet user logout by session on the DRF? -
How to set attr from model field in forms in django
How to set specific attribute for html template based on model method return value or just a model field name? I have already known it's possible to override fields by __init__ function or widgets like this: models.py class Item(models.Model): title = models.CharField(verbose_name=u"name", max_length=200, blank=False, null=False) def __str__(self): return ("%s" % self.title) forms.py class ItemForm(forms.ModelForm): class Meta: model = Item fields = ['title',] widgets = { 'title': forms.RadioSelect(attrs={ 'class': 'radioselect', 'item_name': 'title name?' # <- i want to have title name here of each not statis string }), } def __init__(self, *args, **kwargs): super(ItemForm, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs.update({ 'item_name': '' # <- i want to have title name here of each not statis string }) however, I want to set specific field name, based on previosly defined fields in model not just a static string like in above-mentioned example. If i add Item into a database with title = "Apple" i want to insert this string into this attribute to have such expected result like this in templates: <input type="radio" class="radioselect" item_name="Apple"> -
html page to download checkbox values(appending Y/N in values according to checked status) as a text file in specific folder
I have to develop a webpage with below requirements: A html form with 10 different checkbox in a table format Each check box is pre-checked with default value as "Y" When a user uncheck the checkbox, default value should display as "N" and vice versa There is a submit button in the bottom of the page, when clicked, all the values of checkbox(including unchecked) should be appended by Y if checked and N if unchecked, and then downloaded in a text file in a specific location. Example : [Checkboxes] Elements Enabled [Checked] Bob Y [Unchecked] Mary N [Checked] Marlo Y The text file should contain bobY MaryN MarloY Also, when submit button is clicked, user should be prompted with a pop-up saying "File is downloaded in the path : "The Path" " Thanks in Advance