Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve " The filename, directory name, or volume label syntax is incorrect: '"C:'"
i tried many ways but still got this Could not install packages due to an EnvironmentError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '"C:' Command ""C:\Users\Umair Zia\PycharmProjects\untitled1\venv\Scripts\python.exe" "C:\Users\Umair Zia\PycharmProjects\untitled1\venv\lib\site-packages\pip-19.0.3-py3.8.egg\pip" install --i gnore-installed --no-user --prefix "C:\Users\Umair Zia\AppData\Local\Temp\pip-build-env- g4hyspvc\overlay" --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pyp i.org/simple -- wheel setuptools Cython>=0.29.13 "numpy==1.13.3; python_version=='3.5' and platform_system!='AIX'" "numpy==1.13.3; python_version=='3.6' and platform_system!='AIX'" "nump y==1.14.5; python_version=='3.7' and platform_system!='AIX'" "numpy==1.17.3; python_version>='3.8' and platform_system!='AIX'" "numpy==1.16.0; python_version=='3.5' and platform_system== 'AIX'" "numpy==1.16.0; python_version=='3.6' and platform_system=='AIX'" "numpy==1.16.0; python_version=='3.7' and platform_system=='AIX'" "numpy==1.17.3; python_version>='3.8' and platf orm_system=='AIX'" pybind11>=2.4.0" failed with error code 1 in None -
Django form to save m2m additional fields (using custom through/intermediary model)
I have a "Parent" model, which contains multiple "Child" models and the relationship between Parent and Child holds the order of the children. Thus, I need a custom intermediary model. models.py: class Parent(models.Model): name = models.CharField children = models.ManyToManyField(Child, through=ParentChild) ... class Child(models.Model): name = models.CharField() ... class ParentChild(model.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) child = models.ForeignKey(Child, on_delete=models.CASCADE) order_of_child = IntegerField(null=True, blank=True, unique=True, default=None) A Parent object is created based on a form and the Child objects to be part of the Parent object are selected by checkboxes. Now my questions are: How can the order_of_child be included in the form and rendered alongside the checkboxes and how can the relationship be correctly saved in the view? forms.py: class ParentForm(ModelForm): class Meta: model = Parent fields = ['name', 'children'] def __init__(self, *args, **kwargs): super(ParentForm, self).__init__(*args, **kwargs) self.fields['name'] = forms.CharField(label='Name', widget=forms.TextInput() self.fields['children'] = ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple(queryset=Child.objects.all()) -
django send mail with formular
I want the user to send an email if he has a question about a product etc. So I did all things I know about it and set the host inside the settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 465 EMAIL_HOST_USER = 'name@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = False EMAIL_USE_SSL = True In the views.py I checked if the config was right and send an email to myself with send_mail('things', 'sub', 'message', 'mail@gmx.de' , ['name@gmail.com'], fail_silently=False) So now I made an mail formular where the user can iput his name, email and the message <form method="POST" action="/contact/"> {% csrf_token %} <div class="row mb-3"> <div class="col"> <label>name * </label> <input type="text" class="form-control" placeholder="name" name="conName"> </div> <div class="col"> <label>message *</label> <input type="text" class="form-control" placeholder="message" name="conText"> </div> </div> <div class="mb-3"> <label>Email-Adresse * </label> <input type="email" class="form-control" placeholder="pablo@picasso.de" name="conEmail"> </div> </div> <button type="submit" class="btn btn-outline-success">Abschicken</button> </form> Now I need to change the views.py that the user input is placed and sended: from django.shortcuts import render from django.core.mail import send_mail, EmailMultiAlternatives # from .models import Contact_formular def contactFormular(request): return render(request, 'contact.html',{}) if request.method == 'POST': name = request.POST['conName'] email = request.POST['conEmail'] message = request.POST['conText'] send_mail('New request', name, message, email , ['name@gmail.com'], fail_silently=False) But the form isnt … -
Django rest Framework empty response with gunicorn, but works with runserver
I am trying to implement an Oauth2 authentication using django-oauth-toolkit, and the key exchange works when I am using the built-in django server. However, when I am using gunicorn, I have an empty response. All the other endpoints work fine with gunicorn: view.py from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import AllowAny import requests from .serializers import CreateUserSerializer @api_view(['POST']) @permission_classes([AllowAny]) def register(request): ''' Registers user to the server. Input should be in the format: {"username": "username", "password": "1234abcd"} ''' # Put the data from the request into the serializer serializer = CreateUserSerializer(data=request.data) # Validate the data if serializer.is_valid(): # If it is valid, save the data (creates a user). serializer.save() # Then we get a token for the created user. # This could be done differentley r = requests.post('http://127.0.0.1:8000/o/token/', data={ 'grant_type': 'password', 'username': request.data['username'], 'password': request.data['password'], 'client_id': get_client_id(), 'client_secret': get_client_secret(), }, ) return Response(r.json()) return Response(serializer.errors) @api_view(['POST']) @permission_classes([AllowAny]) def token(request): ''' Gets tokens with username and password. Input should be in the format: {"username": "username", "password": "1234abcd"} ''' r = requests.post('http://127.0.0.1:8000/o/token/', data={ 'grant_type': 'password', 'username': request.data['username'], 'password': request.data['password'], 'client_id': get_client_id(), 'client_secret': get_client_secret(), }, ) return Response(r.json()) @api_view(['POST']) @permission_classes([AllowAny]) def refresh_token(request): ''' Registers user to the server. … -
How do I create several similar links to products automatically in Django?
Say, I need to output some vacancies alvaible, do I have to create a template for every one of them somehow, or i can do it another way, for example, having one template and adding new id's to urls.py? -
Want to change iframe url parameter using python django
I want to change my iframe src url parameter multiple time using Django i also tried to do that using loop but failed i want to see parameters between 1 to 1000000 Code:- <body> <iframe height="300px" src="https://example.com/id=source/Id_22.pdf"></iframe> </body> Want to chnage in <body> <iframe height="300px" src="https://example.com/id=source/Id_23.pdf"></iframe> </body> <body> <iframe height="300px" src="https://example.com/id=source/Id_24.pdf"></iframe> </body> <body> <iframe height="300px" src="https://example.com/id=source/Id_25.pdf"></iframe> </body> -
Django override admin template delete_confirmation
In my templates/admin/my_app/my_model/ folder I added delete_confirmation.html in which I copied and pasted and added a line <h1>Not permitted</h1> {% extends "admin/base_site.html" %} {% load i18n admin_urls %} {% block breadcrumbs %} <div class="breadcrumbs"> <a href="{% url 'admin:index' %}">{% trans 'Home' %}</a> &rsaquo; <a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ app_label|capfirst }}</a> &rsaquo; <a href="{% url opts|admin_urlname:'changelist' %}">{{ opts.verbose_name_plural|capfirst|escape }}</a> &rsaquo; <a href="{% url opts|admin_urlname:'change' object.pk|admin_urlquote %}">{{ object|truncatewords:"18" }}</a> &rsaquo; {% trans 'Delete' %} </div> {% endblock %} {% block content %} {% if perms_lacking or protected %} {% if perms_lacking %} <h1>Not permitted</h1> <p>{% blocktrans with escaped_object=object %}Deleting the {{ object_name }} '{{ escaped_object }}' would result in deleting related objects, but your account doesn't have permission to delete the following types of objects:{% endblocktrans %}</p> <ul> {% for obj in perms_lacking %} <li>{{ obj }}</li> {% endfor %} </ul> {% endif %} {% if protected %} <p>{% blocktrans with escaped_object=object %}Deleting the {{ object_name }} '{{ escaped_object }}' would require deleting the following protected related objects:{% endblocktrans %}</p> <ul> {% for obj in protected %} <li>{{ obj }}</li> {% endfor %} </ul> {% endif %} {% else %} <p>{% blocktrans with escaped_object=object %}Are you sure you want to delete … -
Using global variables in django testing is a best practice..?
In django testing I have a Imagefield which is used in many test cases, In order to avoid the repetition I have assigned the Imagefile obj to the global variable file = open(os.path.join(settings.BASE_DIR, 'logged_out.jpg'), 'rb') image = {'image':SimpleUploadedFile(name=file.name, content=file.read(), content_type='image/jpeg')} class FeedFormTest(TestCase): def setUp(self): self.user = baker.make(SnetUser) self.data = { 'post_info':'Test_data', } def test_feed_form_is_valid(self): #Option 1 Not working #self.data.update(image) #form = FeedForm(self.data) #Option 2 Not working #form = FeedForm(self.data, image) #Option 3 Working form = FeedForm(self.data, image) #locally defined image in SetUp method instead globally print(form.errors) self.assertTrue(form.is_valid()) When I execute the test it's working only for the image which is defined inside the setUp method of test class. Can you suggest or guide me the method in using the variables effectively without defining it multiple times. As I have other variables too like user credentials -
Django: Fixture already exists?
I'm installing Django fixtures for testing and I keep getting an error saying I'm violating a UniqueConstraint. This data came from python manage.py dumpdata > data.json. It's working on the database side. It's loaded in to a test via fixtures=[], so there's nothing to violate. django.db.utils.IntegrityError: Problem installing fixture '/Users/aaron/Github/foo-server/fooproject/items/fixtures/default_items.json': Could not load invites.InviteCode(pk=01e710b8-05c8-41b3-b9cf-5d059cbe4101): duplicate key value violates unique constraint "invites_invitecode_user_id_key" DETAIL: Key (user_id)=(432d2a2e-6c5d-4502-8c99-86c71a6f45d6) already exists. -
How do i include variables in url inside of Flutter
I want to put the value of email an password in the middle of the url insted of 1111 and 22222. The email and password values comes form text controllers and stored in email and password string. How can i put them in middle of url. I tired ${email} insted of 1111 it gave error only static member can be initialized String email = ""; String password = ""; String url ="http://2i6b753b.ngrok.io/authenticate/1111/22222"; -
Password-Protect Django Delete View
I have a basic DeleteView for the user model, which essentially provides the user with the ability to delete their account. The user delete view looks like this: class UserDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = User template_name = 'User/user_confirm_delete.html' def get_success_url(self): messages.add_message(self.request, messages.INFO, 'You no longer exist.') return reverse_lazy('blog-home') # check if current user is the user being deleted def test_func(self): return self.request.user == self.get_object() and the confirmation form in the template (user_confirm_delete.html): <form method="post">{% csrf_token %} <div class="dual-option-container"> <button class="danger button" type="submit">Delete</button> <a href="{% url 'user-profile' %}" class="button">Cancel</a> </div> </form> I want to have the user enter their password as confirmation before they delete their account. How would I go about doing this? -
How to make a image gallery like of spotify
I want to create a image gallery like of spotify's. For my project's backend I am using django and all that stuff is done. But I don't have any idea like how would I create a image gallery like this? What I want is there will be collage for the whole thing and after I click one of it I can see each picture individually exactly what spotify has done. I can't think of how the frontend should be. Any ideas about how can I do it will be extremely helpful. Thank you very much. -
Django - Relationships in Model. One To One, One To Many, Many to Many. please explain with example
Anyone explains one to one, one to many, many to many relations with example in Django. -
Django - strptime() argument 1 must be str, not None
In my application user is entering his name, email, meeting date and meeting hour and I want to save all these information to my database. But application is not running. I'm getting TypeError: strptime() argument 1 must be str, not None but don't what is the reason. Everything seems like true. models.py: def index(request): context = { 'schedules': Schedule.objects.all() } participant_name = request.POST.get('name') participant_email = request.POST.get('email') meeting_date = request.POST.get('date') meeting_hour = request.POST.get('hour') converted_meeting_date = datetime.strptime(request.POST.get('date'), "%m-%d-%Y") converted_meeting_hour = datetime.strptime(request.POST.get('hour'), "%H:%M") if request.POST.get('participant_email'): Schedule.objects.create( participant_name = request.POST.get('name'), participant_email = request.POST.get('email'), meeting_date = converted_meeting_date, meeting_hour = converted_meeting_hour ) return render(request, 'index.html', context) models.py: class Schedule(models.Model): participant_name = models.CharField(max_length=100) participant_email = models.CharField(max_length=100) meeting_date = models.DateField() meeting_hour = models.TimeField() is_scheduled = models.BooleanField(default=False) def __str__(self): return self.participant_name -
Save file path depending on contents of uploaded file in Django REST Framework
I am trying to save an uploaded file to a specific path, depending on its contents. The file is uploaded to a Django REST Framework API in Base64 format inside a JSON object. The file, if valid, contains a unique id for the Machine model that I want to store in the database and use as part of the path in which this and other relevant files will be saved. The UniqueIDAndInfo file needs to be saved because it doesn't only contain the ID I am talking about. It should be very easy to extract the ID, save it as a field in the model instance, and then tell the Storage system to save the file in a specific directory according to the ID value. I am getting the file using the drf_base64 extension in the following, simple way: class MachineSerializer(serializers.ModelSerializer): class UniqueIDAndInfoBase64File(drf_base64.Base64FileField): pass unique_id_and_info = UniqueIDAndInfoBase64File(allow_null=False, allow_empty_file=False) What I am trying to accomplish is something like this, if the upload_to callback accepted the contents of the file as an argument: def content_file_name(instance, filename, file_contents): # file_contents is not a true argument of this function! unique_id = process_unique_id_and_info_file(file_contents) return os.path.join(MACHINE_FILE_FOLDER, unique_id, 'unique_id_and_info.info') class Machine(models.Model): unique_id_and_info = models.FileField(upload_to=content_file_name) -
Creating A Form From A Forerign Key In Django
Is there a way I can create a form in Django with inclusive of a foreign key which also should be created as the form is filled and not selected? -
Django: Join ManyToManyField with CharField in Frontend
I need to register which passengers are on my ride. Therefor I use the following classed: class Member(models.Model): name = models.CharField(max_length=32) ... class Ride(models.Model): passengers = models.ManyToManyField(Member) ... That way it is easy to select the passengers which are members in the ride. So far so good. But I want to add passengers (just by their name) which are not members as well (without adding new member instances). My guess is to write a custom widget: A comma separated list with an autocomplete for existing members (Select2). Something like the address bar in an email-app. Does anyone know a ready-to-use solution? -
Django admin: How to show calculated value from entered values dynamically in Django admin form page?
I have a form which is having a 'price', 'tax' and 'discount' fields (IntegerFields). And then one more read-only field will be there called 'total_price'. while we enter the 'price', 'discount' and 'tax', automatically 'total_price' value should display. If we change the 'discount' or 'price' then 'total_price' also change immediately. After seeing the final price, we can click the 'Save' button. How to attain this in Django admin? -
How to remove table not found error in django?
I am creating an API in django where i'm trying to make post request through json file and it is throwing error no such table: main.restapi_quiz__old" But there are no such table and i have tried removing all migrations and re-creating it but it's still showing this error. My Model: class QuizCat(models.Model): category_name = models.CharField(max_length=200) class Quiz(models.Model): category_id = models.ForeignKey(QuizCat, on_delete=models.CASCADE) name = models.CharField(max_length=200) class UserDetails(models.Model): user_id = models.IntegerField() Qid = models.ForeignKey(Quiz, on_delete=models.CASCADE) score = models.IntegerField() Why am i getting this error and how can i remove it ? -
Usage of RabbitMQ queues with Django
I'm trying to add some real-time features to my Django applications, for that i'm using RabbitMQ and Celery on my django project, so what i would like to do is this: i have an external Python script which sends data to RabbitMQ > from RabbitMQ it should be retrieved from the Django app. I'm sending some muppet data, like this: connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='Test') channel.basic_publish(exchange='', routing_key='Test', body='Hello world!') print(" [x] Sent 'Hello World!'") connection.close() What i would like to do is: as soon as i send Hello World!, my Django app should receive the string, so that i can perform some operations with it, such as saving it on my database, passing it to an HTML template or simply printing it to my console. My actual problem is that i still have no idea how to do this. I added Celery to my Django project but i don't know how to connect to RabbitMQ and receive the message. Would i have to do it with Django Channels? Is there some tutorial on this? I found various material about using RabbitMQ and Celery with Django but nothing on this particular matter. -
Django with UDP socket - What should I use, Twisted Plugin or Django Channels?
I'm making the Django website and need parsing some data from the UDP socket. I found https://twistedmatrix.com/documents/current/core/howto/tap.html , what can help me handle UDP socket very easy, when I embed it to Django project, it doesn't run. how to embed it to Django? -
Django views: postgres materialized view accessible via get but not via filter (both queryset)
I try to filter materialized postgres views in Django views.py. The database and the views were created with postgres. I can filter views which represent one to many relationships and I can access views with get (queryset) which represent many to many relationships. But I cannot filter those views which represent many to many relationships. Models were created with inspectdb. It's a postgis legacy database. How do I have to filter these views? models.py fid = models.AutoField(primary_key=True) id_dokument = models.IntegerField(blank=True, null=True) dokument = models.CharField(max_length=50, blank=True, null=True) datei = models.CharField(max_length=100, blank=True, null=True) beschreibung = models.CharField(max_length=1024, blank=True, null=True) datum = models.DateField(blank=True, null=True) person = models.CharField(max_length=50, blank=True, null=True) dokumenttyp = models.CharField(max_length=30, blank=True, null=True) id_objekt = models.IntegerField(blank=True, null=True) objekt = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = False # Created from a view. Don't remove. db_table = 'objekt_dokumente_rel' views.py dokumente = ObjektDokumenteRel.objects.using('db').filter(id_objekt=fid) If replacing filter with get I receive one object (as expected). -
How to connect a django app to bokeh server?
I'm currently trying out bokeh server to serve some interactive bokeh charts to my django app, but having difficulty connecting via views.py. The browser returns an OSError: Cannot pull session document because we failed to connect to the server (to start the server, try the 'bokeh serve' command) The server itself returns 404 error for the request: 200-03-31 08:17:09,179 404 GET /ws?bokeh-protocol-version=1.0&bokeh-session-id=ZhGn4XcmC1qDPYtF4SRPGPa1GzSgTqktqmvkIEGJke26 (127.0.0.1) 0.55ms My server is set up as follows: bokeh_server | |--main.py main.py is a very basic bokeh chart main.py from bokeh.io import curdoc from bokeh.layouts import column from bokeh.plotting import figure from bokeh.models.sources import ColumnDataSource source = ColumnDataSource(dict(x=list(range(5)), y=list(range(5)))) p = figure(width=300, height=300, tools=[], toolbar_location=None, name="test") p.line(x='x', y='y', source=source) curdoc().add_root(column(p, sizing_mode='scale_width')) Running the server (bokeh serve bokeh_server) and then opening https://localhost:5006 in a browser renders the chart correctly (https://localhost:5006/bokeh_server) The issue comes when I try to open it from my django app. views.py from django.shortcuts import render from django.http import HttpResponse from bokeh.client import pull_session def testbserver(request): session = pull_session(url="http://localhost:5006/") script = server_session(model=None, session_id=None, url="http://localhost:5006/", ) return render(request, 'testserver.html', {'script':script}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('testbserver/', views.testbserver, name='testbserver'), ] testserver.html {% extends "base_generic.html" %} {% block content … -
ModuleNotFoundError: No module named 'To_do.todos' - DJANGO
So I just started learning django, and I was learning from this youtube video: https://www.youtube.com/watch?v=Nnoxz9JGdLU So here is my directory map: To_do +To_do +_pycache_ +_init_.py +asgi.py +settings.py +urls.py +wsgi.py +todos +_pycache_ +migrations +_init_.py +admin.py +apps.py +models.py +tests.py +urls.py +views.py +db.sqlite3 +manage.py code of To_do/To_do/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('todos/', include('todos.urls')) ] code of To_do/todos/urls.py from django.urls import path from . import views urlpatterns =[ path('list/',views.list_todo_items) ] code of To_do/todos/view.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def list_todo_items(request): return HttpResponse('from list_todo_items') My Issue: After using the above codes with re-directions, clearly i'm messing up somewhere, as in the "main" urls.py file present in the project directory, when I'm running my server i get the error: $ python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/smith/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/smith/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/smith/.local/lib/python3.6/site-packages/django/core/management/base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "/home/smith/.local/lib/python3.6/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/home/smith/.local/lib/python3.6/site-packages/django/core/checks/registry.py", … -
How to delete record from database by using input form in django
So i have this small web program in which a user can enter his/her email and receives some updates. Nevertheless this email is saved in the database (sqlite3) and i have a form in which a user can unsubscribe, my problem is i'm trying to find a way to take the input from the unsubscribe form & if it matches any record in the database it deletes it. Does anyone have any suggestions? This is the view i'm trying to create but doesn't work def unsubscribe_view(request): form = EmailForm() if request.method == "POST": form = EmailForm(request.POST) value = form.cleaned_data['email'] if form.is_valid(): Email.objects.filter(email = value).delete() context = { 'form' : form, } return render(request, 'Version/unsubscribe.html', context) This is the html page <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <div style="text-align : center;"> <h1> UnSubscribe Page </h1> <div class="container"> <div class="row"> <form method="post" action="/"> {% csrf_token %} {{form}} <button type="submit" class="waves-effect waves-light btn-small">Unsubscribe</button> </form> </div> </div> </div> This is the model if its any helpful from django.db import models # Create your models here. class Email(models.Model): email = models.EmailField() def __str__(self): return self.email This is the form from django import forms from django.forms import ModelForm from .models import …