Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django(Python) registration doesnt work correctly
I am trying to write right registration for my online store with confirmation via mail. Registration passes once a time, but after I click on "Register", the same registration page is loaded, so activation proccess doesnt starting. But a new user is wrote into the database with such data (and this does not work every time), but I cannot enter the site with same data. This is my first site with registration, so it’s hard to find whats wrong. Thanks for help. Attach the code: models.py: from django.db import models from django.contrib.auth.models import AbstractUser from django.dispatch import Signal from .utilities import send_activation_notification class AdvUser(AbstractUser): is_activated = models.BooleanField(default = True, db_index = True, verbose_name = 'Activated?') send_messages = models.BooleanField(default = True, verbose_name = 'Agreement for promotion messages') class Meta(AbstractUser.Meta): pass user_registrated = Signal(providing_args=['instance']) def user_registrated_dispatcher(sender, **kwargs): send_activation_notification(kwargs['instance']) user_registrated.connect(user_registrated_dispatcher) forms.py: from django.contrib.auth import password_validation from django.core.exceptions import ValidationError from django import forms from .models import AdvUser from .models import user_registrated class RegisterUserForm(forms.ModelForm): email = forms.EmailField(required = True, label = 'Email') password1 = forms.CharField( label = 'Password', widget = forms.PasswordInput, help_text = password_validation.password_validators_help_text_html() ) password2 = forms.CharField( label = 'Reenter password', widget = forms.PasswordInput, help_text = 'Reenter your password' ) def clean_password1(self): password1 … -
one to many django add Authors to book
I have a bookstore, I want to add several Authors to add a new book .how can I do this?my code just accept one Authors class Authors(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) class Book(models.Model): title = models.CharField(max_length=200) topic = models.CharField(max_length=200) author = models.ForeignKey(Authors, on_delete = models.DO_NOTHING) -
How to answer interpreter question using python for django
I am trying to create a program that will create a superuser in Django. Ishould use python manage.py createsuperuser and then it asks the username that you want and ... . So I want my python program to answer it itself using the variables that it has. My program doesn't work when the question pops out. My program so far : import subprocess email = 'email@gmail.com' username = 'username' password = 'password' response = _subprocess.Popen.communicate('python manage.py createsuperuser') if 'no such table: auth_user' in response or 'python manage.py migrate' in response : print('you need to migrate the database first') else : subprocess.Popen.communicate(input='username') _subprocess.Popen.communicate(input='password') _subprocess.Popen.communicate(input='tsp5majidi@gmail.com') -
Can't figure out NoReverseMatch error in Django
I've written a small web application and when I want to load the page I get Reverse for 'form_view' with arguments '('',)' not found. 1 pattern(s) tried: ['form/view/(?P[0-9]+)$'] The application was working fine. I can't figure out what went wrong. I checked for typos and naming mistakes. I didn't find anything. I can't figure out if there's something wrong with the url pattern or not. The error started after I updated the database with a new entry. Models.py class Form(models.Model): name = models.CharField(max_length = 200) publish_date = models.DateField() book_length = models.IntegerField() first_publish = models.BooleanField() def __str__(self): return self.name def get_absolute_url(self): return reverse('form_edit', kwargs={'pk': self.pk}) urls.py urlpatterns = [ path('', views.FormList.as_view(), name='form_list'), path('view/<int:pk>', views.FormView.as_view(), name='form_view'), path('new', views.FormCreate.as_view(), name='form_new'), path('edit/<int:pk>', views.FormUpdate.as_view(), name='form_update'), path('delete/<int:pk>', views.FormDelete.as_view(), name='from_delete'), ] views.py class FormList(ListView): model = Form class FormView(DetailView): model = Form class FormCreate(CreateView): model = Form fields = ['name', 'publish_date', 'book_length', 'first_publish'] success_url = reverse_lazy('book_list') class FormUpdate(UpdateView): model = Form fields = ['name', 'publish_date', 'book_length', 'first_publish'] success_url = reverse_lazy('book_list') class FormDelete(DeleteView): model = Form success_url = reverse_lazy('book_list') form_list.html - one of the templates where the traceback tells me I have the error at <td><a href="{% url "form_view" form.id %}">view</a></td> <h1>Books</h1> <table border="1"> <thead> <tr> <th>Name</th> <th>Publish … -
How to save an image in a directory named on the User?
I am using Django2.2 and I am currently learning Django. I have created a model where I have to post an image of a certain thing and that model is connected with a User. I want to save the image on a directory named on that certain user I have a custom User Model where I created a field called Profile Photo and that profile photo is saved to a directory named on that User.But then I created another application called 'Product' and there I created many fields including an image field.I am trying to save that image on that directory named on that specific User. def user_directory_path(instance, filename): return 'media/%s/%s' % (instance.username, filename) class Products(models.Model): title = models.CharField(max_length=100) body = models.CharField(max_length=1000) image = models.ImageField(upload_to = user_directory_path) product_user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title When I try to save a Product and error occurs. 'Products' object has no attribute 'username' Is there any successful ways to do it. -
django restframework search_filter search content with space
data likes [ {"data": {"line": "10", "no": "10"} }, # I want to get this one {"data": {"line": "11", "no": "10"} } ] Use search_filter filter data field, search "line": "10", In the backend, search term will be split by space, and return two record above. # rest_framework.filters.SearchFilter#filter_queryset search_terms = {list} <class 'list'>: ['"line":', '"10"'] 0 = {str} '"line":' 1 = {str} '"10"' I want to search them as a whole word, How to do that? -
How Can i remove App Name from django Admin Panel?
Actually i want to remove app names from django admin panel how can i achieve this?? -
How can i Add captcha to my Html form using Django
I have already made a website with Django but unable to add captcha with Django and link it with html template -
After setup nginx assets folder not found (Django)
I was trying to set up Nginx + gunicorn + Django in a ubuntu private server by following this link Here is my /etc/nginx/sites-available file server { listen 80; server_name 192.168.0.157; location = /favicon.ico { access_log off; log_not_found off; } location /assets/ { root /home/isho/ishoErp/production; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Here is my settings.py file STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'assets') ] I have a assets folder. everything works fine but assets file not found. what I'm doing wrong? -
How to set globally-accessible context variables in django template tags?
There is a template tag which returns a random element from the list. I also need to save all the elements that were in the list and the one that had been picked in context, and later depict that information in django-debug-toolbar panel. from django import template import random register = template.Library() @register.simple_tag(takes_context=True, name='pickrandomelementtag') def pickrandomelementtag(context, list_of_random_elements): context.dicts[0]["key18"] = "value19" return random.choice(list_of_random_elements) So I test setting the variables functionality with given line: context.dicts[0]["key18"] = "value19" I am able to access the {{key18}} within the template, but my aim is set this variable in a manner that it would be accessible later on (globally?) from django-debug-toolbar panel. That's where i'm stuck. Here is my django-debug-toolbar panels.py file: from debug_toolbar.panels import Panel from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from django.template.response import SimpleTemplateResponse class RandomPanel(Panel): name = "RandomPanel;" has_content = True template = 'panels/randompanel.html' def title(self): return _('Random Panel') def generate_stats(self, request, response): print('that is where I need to access key18') self.record_stats( { "request": request } ) How would I access context variable key18 in generate_stats method of RandomPanel class object? Or maybe context is a wrong place to set custom cariables within template tags and you'd advise other … -
How to set 'DJANGO_SETTINGS_MODULE' based on mysite.settings from a different directory
I have a Django project which works good. My manage.py and mysite folder (the one that includes the following: __init__.py settings.py urls.py views.py wsgi.py ) and a bunch of django app folders are located in the following directory E:\mydjangoproject In order to use the django setting of this project in a script, I used to use the following code at the beginning of that script: os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' which always works fine since the python script file which I was running was also located in the directory E:\mydjangoproject and it locates the mysite folder as a module and its settings perfectly. My question is what if I am trying to run that exact python script from another directory say E:\mydjangoproject\SubFolder 1\SubFolder 2\ and still want the os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' Off course when I try this I get the error ModuleNotFoundError: No module named 'mysite'. How can I pass the right path of the django settings to the script? -
Django rest hyperlinks for foreign key
Im trying to connect 2 objects using hyperlinks. I have a Company object and a 'Client' object, a company has multiple clients, so the models.py looks like this: models.py: class Company(models.Model): name = models.CharField(max_length=200) lookup_field = 'id' def __str__(self): return self.name def get_absolute_url(self): return reverse('common_app:company-detail', kwargs={'id': self.id}) class Meta: ordering = ['-id'] class Client(models.Model): image = models.ImageField() name = models.CharField(max_length=200) company = models.ForeignKey(Company, on_delete=models.SET_NULL, null=True, default=None) verified = models.BooleanField(default=False) def __str__(self): return self.name serializers: class CompanySerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="common_app:company-detail") read_only = ('id', ) class Meta: model = Company fields = '__all__' class ClientSerializer(serializers.HyperlinkedModelSerializer): company = serializers.HyperlinkedRelatedField(read_only=True, view_name='common_app:company-detail') read_only = ('id', ) lookup_field = 'id' class Meta: model = Client lookup_field = 'id' fields = ('url', 'name', 'company') views.py: class CompanyViewSet(BaseModelViewSet): serializer_class = CompanySerializer queryset = Company.objects.all() lookup_field = "id" class ClientViewSet(BaseModelViewSet): serializer_class = ClientSerializer queryset = Client.objects.all() lookup_field = "id" urls.py: app_name = 'common_app' router = DefaultRouter() router.register('client', ClientViewSet, basename='client') router.register('company', CompanyViewSet, basename='company') for url in router.urls: print(url.__dict__) urlpatterns = [ path('api/', include(router.urls)), ] I cant understand what is going wrong (i tried to put the lookup_field everywhere) but i get: E django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "client-detail". You may have failed to include … -
Saving / accessing fields from Class methods (Django)
Appologies for the beginner question and/or stupidity - I'm learning as I go.... I'm trying to pass a user entered url of a PubMed article to access the metadata for that article. I'm using the following code, but I cannot access anything form the save method in he 'Entry' model. For example in my html form I can display {{entry.date_added }} in a form but not {{ entry.title}}. I suspect it's a simple answer but not obvious to me. Thanks for any help. models.py from django.db import models from django.contrib.auth.models import User import pubmed_lookup from django.utils.html import strip_tags class Topic(models.Model): """Broad topic to house articles""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): """Return a string representation of the model""" return self.text class Entry(models.Model): """Enter and define article from topic""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) pub_med_url = models.URLField(unique=True) date_added = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): query = self.pub_med_url email = "david.hallsworth@hotmail.com" lookup = pubmed_lookup.PubMedLookup(query, email) publication = pubmed_lookup.Publication(lookup) self.title = strip_tags(publication.title) self.authors = publication.authors self.first_author = publication.first_author self.last_author = publication.last_author self.journal = publication.journal self.year = publication.year self.month = publication.month self.day = publication.day self.url = publication.url self.citation = publication.cite() self.mini_citation = publication.cite_mini() self.abstract = strip_tags(publication.abstract) super().save(*args, **kwargs) class … -
How to get thumbnail of mp4 when upload it with `django-storages`?
I work on local.py I can get instance.video.path and be able to get the thumbnail. Here are my function, testcase, and model utils.py def save_screen_shot(instance: Video) -> Video: try: filename = instance.video.path except ValueError as err: logger.info(f"The 'video' attribute has no file associated with it.") else: video_length = clean_duration(get_length(filename)) instance.video_length = video_length img_output_path = f"/tmp/{str(uuid.uuid4())}.jpg" subprocess.call(['ffmpeg', '-i', filename, '-ss', '00:00:00.000', '-vframes', '1', img_output_path]) # save screen_shot with open(img_output_path, 'rb') as ss_file: instance.screen_shot.save(str(uuid.uuid4()) + '.jpg', ss_file) instance.save() finally: instance.refresh_from_db() return instance tests.py def test_screen_shot(self): client = APIClient() client.force_authenticate(user=self.user_a) with open('media/SampleVideo_1280x720_1mb.mp4', 'rb') as mp4_file: data = { 'text': "Big Bug Bunny", 'multipart_tags': 'Tri Uncle featuring', 'video': mp4_file, } url = reverse('api:tweet-list') res = client.post(url, data=data, format='multipart') video = Video.objects.first() mp4_file.seek(0) # set head to first position before do an `assertion` assert status.HTTP_201_CREATED == res.status_code assert mp4_file.read() == video.video.read() assert video.screen_shot # Not None assert 1 == Video.objects.count() models.py class Video(models.Model): video = models.FileField(upload_to='./videos/', null=True, blank=True) I put debug and found that in my production INSTALLED_APPS has 'storages' in it. And it raise me the error ipdb> instance.video.path *** NotImplementedError: This backend doesn't support absolute paths. ipdb> dir(instance.video) ['DEFAULT_CHUNK_SIZE', '__bool__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', … -
Internal Server Error when running Django with Scrapy
I am making a relatively simple django app where you can add articles to it. Besides adding the article manually i am attempting to make use of scrapy and after you have added the title of the article manually you would visit the page of the article from the front-end and by the push of a button it would crawl another website to find that article and copy specific links it would find. The problem is that i am facing several issues that results in Internal Server Error. The errors are ValueError: signal only works in main thread when I am not using the options --noreload --nothreading to run the django server. When running the server with the options mentioned just before, i get raise error.ReactorNotRestartable() twisted.internet.error.ReactorNotRestartable. I would not like to have to use the options --noreload --nothreading to run the django server in general as I read that it limits performance a lot. I made a seperate app in my django project to keep things clean. The views.py I am using is the following from django.shortcuts import render, get_object_or_404 from django.urls import reverse_lazy from templates import * from .models import * import scrapy from scrapy.crawler import CrawlerProcess def … -
How do I add one model objects to another model’s ModelForm template with many to one relationship in Django?
I am trying to create a Hospital Management System in which have Two ModelForms, one ModelForm creates Patient Object, And another form of model two is used to admit that Patient which means it uses Patient Objects in New Form Template with new fields and creates new ID Which have model one id(patient ID) and model two id(IPD ID )as well and model two is linked with model one with Patient Id,one patient can have multiple Ipd id -
How to implement a shared variable for the entire django project?
I am writing a django server for a card game. The game begins when 2 players press the play button. To do this, in views.py I have the variable "turn", in which the id of the player who wants to play is recorded. As soon as 2 players appear in the "turn", an instance of the class with the game is created for them and is written into the dictionary, for example: games_now = {"id1": , "id2": }. Thus, 2 players use one class and manipulate common variables in it. So far, I run django as "manage.py runserver 0.0.0.0:80" on the server 1 core and do not notice any problems. But in production I have to use apache or nginx. What happens if I run a django-project on nginx on a multi-core VPS? Will all players then have access to the "turn" and "games_now" variables? How can I implement the functionality of the game on a multi-core processor to avoid conflicts? The game is implemented in the bot on vk.com I receive requests from vk.com in the form {"from_id": from_id (int), "objects": {"message": message (text)}} and within 3 seconds I should return the answer 'ok' to the server. Therefore, everything … -
Django Models, on delete set pk
This is my models: class Customer(models.Model): nome = models.CharField(max_length=40) indirizzo = models.CharField(max_length=40) class Appo(models.Model): appo = models.CharField(max_length=40) customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True, default=1,related_name='appocli') now, if I delete a Customer I need SQL set in Appo models a specific PK for customer Foreign Key. For example 1. Something like: on delete set 1 Please help -
I forget on which virtual environment i was working on?
I have several virtual environment in my computer and i have forget the name of the virtual environment i was working on and i don't know how can i know the name of the environment. Can someone help me please -
How to create a seperate table for the user when they registered on site
I have to create a site where every user store's there data and each user get the isolated storage for which i have to allot a particular table to each user, as the size of data stored by user is big enough too and I doesn't now how to do it in django. Please suggest me the same. -
How to upload a file from django view using filepath
I have to upload a file from django views using the file path from the local system. I'm using models.create method to save the filepath. But the image is not getting uploaded into the media directory. I have tried the Content and File from django core.utils but it deos not work def createevent(request): file_path = os.path.join(settings.FILES_DIR) # Getting the directory with files f = [] for (dirpath, dirnames, filenames) in walk(file_path): f.extend(filenames) break f.remove(".DS_Store") img = random.choice(f) # Select a random file pa = os.path.abspath(img) # absolute file path # pa = (img,File(pa)) response = File(pa) print(pa) loc = "School Ground" if request.method == 'POST': get_dateof = request.POST.get('dateof') get_nameof = request.POST.get('nameof') get_descof = request.POST.get('descof') new_report = Event.objects.create( name=get_nameof, description=get_descof, location=loc, timeoftheevent=get_dateof, user=request.user, image= pa ) #creating a db record return HttpResponse('') -
scope in django_channels searches for an argument on all pages from URLRouter
I need to support multiple-page socket connection, URLRouter is like this: URLRouter([ path('device/<device_name>',IndicatorConsumer), path('add',IndicatorConsumer), path('', IndicatorConsumer) ]) consumers.py is async def websocket_connect(self,event): print('connection succefull ', event) await self.send({ 'type': 'websocket.accept' }) self.device_id = self.get_device_id(self.scope['url_route']['kwargs']['device_name']) I need to get device_name via scope to send it to another function. But for some reason the scope searches for this on all the pages that are in the URLRouter, and so, for example, in the /add socket immediately closes because it can not find there device_name Everything works fine on the device pages, others get an error: Exception inside application: 'device_name' -
Insert multiple values with unique record in database in Django
I have a form in which user selects value from downtown and insert one value from text box. I have made a text-box such that user can enter multiple values by adding it. like in pic But when I submit form it saves only one record in database with value of last text box. Can anyone tell me how to save each value in database with unique record. my view:- class PerticularCreatView(LoginRequiredMixin,SuccessMessageMixin,CreateView): model=Perticular success_message = " Perticulars Added successfully!" reverse_lazy('add-perticular') template_name = 'add-perticular' form_class = PerticularCreateForm # fields =[] def get_context_data(self, **kwargs): kwargs['perticulars'] = Perticular.objects.filter(is_del=0).order_by('-perticular_crt_date') return super(PerticularCreatView, self).get_context_data(**kwargs) def form_valid(self,form): form.instance.perticular_crt_by = self.request.user return super(PerticularCreatView, self).form_valid(form) -
Django website deploying to heroku. Application error
I'm trying to deploy my django website to heroku but I get an Application Error shown on the webpage. Looking at my logs using heroku logs --tail (what it tells me to do on webpage), I recieve an error 2019-07-27T06:14:34.046386+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=prremia.herokuapp.com request_id=20cd473d-50c2-43b6-892e-ce8f8981229d fwd="49.36.8.33" dyno= connect= service= status=503 bytes= protocol=https 2019-07-27T06:14:34.878053+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=prremia.herokuapp.com request_id=53c5e449-ba17-4e93-86f9-7b70eeb7e074 fwd="49.36.8.33" dyno= connect= service= status=503 bytes= protocol=https I followed the instructions from Django's docs. Django 2.2.3 Python 3.7.3 Heroku-18 My webpage: -
Django safe and striptags don't work properly
if don't have seo description,post.conten|trunnchars:160 show it. However, i have uniode and charset problem Turkish characters like " ş Ş İ I ö Ö ü Ü ç Ç " doesn't work properly the result is for Ö= &#214; ı= &#305; i added <meta charset="utf-8"> {% block description %}{% if post.seo_description %}{{post.seo_description|truncchar:160}}{% else %}{{ post.content|truncatechars:160 |safe|striptags}}{% endif %}{% endblock %}