Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I tried to create my first django project(using powershell) but failed to do so because of errors
I am new to django. I wanted to create my first sample project so I followed all the usual ways(as in youtube) and installed python 3.4,pip,django etc. When the environment was set I typed the below command in windows powershell django-admin startproject mysiteone and got the below syntax error message(See last para) My system uses Windows 7 OS. I was unable to find even the version of django i had installed. I dont know why. I gave these codes in powershell: django-admin startproject mysiteone python -m django --version Error message that I got as a result: Traceback (most recent call last): File "C:\Python34\lib\runpy.py", line 171, in _run_module_as_main "_main_", mod_spec) File "C:\Python34\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Python34\Scripts\django-admin.exe\_main_.py", line 5, in <module> File "C:\Python34\lib\site-packages\django\core\management\_init_.py", line 260 subcommands = [*get_commands(), 'help'] SyntaxError: can use starred expression only as assignment target -
Django-Haystack not returning exact query
I'm trying to fix my Django-haystack combined with Elasticsearch search results to be exact. The problem I have now is that when a user try for example, the "Mexico" query, the search results also returns deals in "Melbourne" which is far from being user-friendly. Anyone can help me to fix this problem? This is what I've tried so far but no good results: My forms.py from haystack.forms import FacetedSearchForm from haystack.inputs import Exact class FacetedProductSearchForm(FacetedSearchForm): def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.ptag = data.get('ptags', []) self.q_from_data = data.get('q', [''])[0] super(FacetedProductSearchForm, self).__init__(*args, **kwargs) def search(self): sqs = super(FacetedProductSearchForm, self).search() # Ideally we would tell django-haystack to only apply q to destination # ...but we're not sure how to do that, so we'll just re-apply it ourselves here. q = self.q_from_data sqs = sqs.filter(destination=Exact(q)) print('should be applying q: {}'.format(q)) print(sqs) if self.ptag: print('filtering with tags') print(self.ptag) sqs = sqs.filter(ptags__in=[Exact(tag) for tag in self.ptag]) return sqs My search_indexes.py import datetime from django.utils import timezone from haystack import indexes from haystack.fields import CharField from .models import Product class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField( document=True, use_template=True, template_name='search/indexes/product_text.txt') title = indexes.CharField(model_attr='title') description = indexes.EdgeNgramField(model_attr="description") destination = indexes.EdgeNgramField(model_attr="destination") #boost=1.125 link = indexes.CharField(model_attr="link") image = indexes.CharField(model_attr="image") … -
Send message to several groups using Django Channels
I'm building a chat app. I'd like to know: 1) If the way I'm currently implementing chat is incorrect / bad coding practice 2) How to send the message to several groups The base idea is the following: Each user connects to a specific channel (.../ws/), and is part of a specific group One group contains one user, and a user can only participate to one group When a user sends a message to another user, they also send a list of user IDs to whom the message should be transferred. The message is then sent to the different groups I'd like to send the message to those users in an efficient/scalable way. Below is the current way I'm implementing chat where the message is sent to one user (only 1 user is specified in data[userID]) def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): print('Websocket received info!') data = json.loads(text_data) # Send the message to the specified user self.send_channel_message(data[userID], data['message']) def send_channel_message(self, group_name, message): async_to_sync(self.channel_layer.group_send)( '{}'.format(group_name), # Specify intented group { 'type': 'channel_message', 'message': message } ) def channel_message(self, event): message … -
How to send django form data to flask api
I need to send data to a flask url but I keep getting the error working outside of request context. How do I send the data from the form to the url? views.py: def home(request): if request.method == 'POST': form = NameForm(request.POST) # logging.info(form) if form.is_valid(): logging.info("before req: " + str(jsonify(form))) response = flask_request.post('http://127.0.0.1:5000/vin/exists/', params=jsonify(form)) data = response.json() else: form = NameForm() return render(request, 'post/form.html', {'form': form}) -
How to store list data into the database using django
I have django model with one field calle tag_name and with the forms i am taking input from the user like below: Now in the views.py i got the input from the user whatever he passed and i have splited into the list like this: with this i am storing data in to the table like this: but i want to add these 2 name in to the table as seperated rows something like this: what can i do in the views.py file or in to the model to make this happen? -
How to Serve Django Application With Apache2 and Mod WSGI
I want to serve my Django applications using Apache2 and the mod_wsgi module. I have setup an Apache virtualhost at /etc/apache2/sites-available/mysite.confand I have made some configuration changes to WSGI at home/username/development/mysite/mysite/wsgi.py However, when I navigate to mydomain.com, I am being presented with the 500 Internal Server Error: The server encountered an internal error or misconfiguration and was unable to complete your request.. I am very new to server development and have never used Apache2 before so I am unsure as to where I have gone wrong in my configuration. Below you will find my virtualhost configuration file as well as my WSGI file. Additionally, I have provided the structure layout of my project directory in case this helps. Any help is greatly appreciated. directory structure >> home >> username >> development >> mysite >> mysite >> settings.py >> wsgi.py >> website >> static >> manage.py >> venv mysite.conf <VirtualHost *:80> ServerName mydomain.com DocumentRoot /home/username/development/mysite WSGIScriptAlias / /home/username/development/mysite/mysite/wsgi.py WSGIDaemonProcess mydomain.com processes=2 threads=15 display-name=%{GROUP} python-home=/home/username/development/venv/lib/python3.5 WSGIProcessGroup mydomain.com <directory /home/username/development/mysite> AllowOverride all Require all granted Options FollowSymlinks </directory> Alias /static/ /home/username/development/mysite/website/static/ <Directory /home/username/development/mysite/website/static> Require all granted </Directory> </VirtualHost> wsgi.py import os import time import traceback import signal import sys from django.core.wsgi import get_wsgi_application … -
Real time quiz web application using django
I need help in developing a real-time quiz application in Django. User(s) can participate in it according to to the admin, like a real-time competition. -
Generic View Not able to load and throws TemplateDoesNotExist error
I'm trying to use the Generic views in Django. This is a part of the tutorial on the official Django site. I've been at this problem for a few hours now and somehow the other answers on this website and others don't seem to solve my problem. The index.html file is working as localhost:8000/polls loads successfully but anything after that throws the TemplateDoesNotExist error. I don't know why when it tries to load a Generic view, it fails. I also tried removing the index.html file but still the Generic View failed to load I'll probably put up everything of concern here: My settings.py file: import os SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'v(wm5xfr8x3zr-5=vdezxz#_!74w=!^8l1#^r68-fm%%nqg)+1' DEBUG = True TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) TEMPLATE_DIRS = ( "C:/Django/mysite/templates/polls/", ) ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'pankaj29', 'HOST': … -
How can a model have multiple keys with the same type of models as values?
I'm making an application and I should make a Model which have 2 keys that saves models of the same type. It's not easy to express in English so I will upload the image of the situation. In Food Pair Model ( or we can call it table I think ) I want to refer Food Model But I can't use ForeignKey or ManyToManyField. I don't know what database relation to use in this case and how to make it. What can I use for this case? -
How to update only field in drf
I'm trying to update a field of my model, im trying use patch for this, but i'm new to django rest and i think i'm having something wrong Im try use partial_update method but doesn't work. I want update status for canceled(canceled is in my enums.py ) This is part of my model class Aula(AcademicoBaseModel, permissions.AulaPermission): turma_disciplina = models.ForeignKey(TurmaDisciplina, models.PROTECT, related_name='lessons') data_inicio = models.DateTimeField(db_index=True) data_termino = models.DateTimeField() duracao = models.IntegerField(default=50) status = models.ForeignKey('Status', models.PROTECT, default=1) This is my view class CancelLessonView(generics.UpdateAPIView): serializer_class = serializers.AulaSerializer def patch(self, request, *args, **kwargs): lesson = self.kwargs.get('id') instance = models.Aula.objects.get(id=lesson) status = models.Status.objects.get(id=enums.StatusEnum.CANCELLED) instance.status.id = enums.StatusEnum.CANCELLED instance.status.name = status.name instance.status.color = status.color instance.status.ignore_in_attendance_report = status.ignore_in_attendance_report instance.status.allow_attendances = status.allow_attendances instance.status.allow_activities = status.allow_activities serializer = serializers.AulaSerializer(data=request.data, partial=True) serializer.is_valid(raise_exception=True) self.perform_update(serializer) instance.save() return Response(serializer.data) -
how to play audio using javascript , HTML , AJAX
I am trying to embed the audio player in my website . The requirement of this is when the user selects other page the audio should still play in the background unless user pause for it. I guess the terminology for this is Persistence audio player . not sure though. Can anyone provide some example how to achieve this one? I guess I have to use AJAX for this , if I am not wrong. Thank you -
How to only display one part of a class and iterate through it with a button
So basically I am basically trying to output one scene at a time in a story app. I have created a model that has a Story, Scene, and Choices. The Story has a title, and the scenes are related to the story via foreign-key, and the choices are related to the scenes via foreign-key. After finally being able to display all the scenes to their designated Story, and choices to their designated scene How would I be able to 1). Show only one scene at a time? Because the problem I'm facing is looping through them but it displays all the scenes and their possible choices under them but I would not like the user to see the next scene until they have answered so that when they hit submit if it has x boolean then I want it to either stop or continue the story depending on their answer 2). How do I show the choice they chose displayed with the next scene? I am really new to Django and trying my best to use class views as I've heard they are best in the long run of things but I don't understand how I would in this case? … -
How can I autofill author with a model form (video upload)
I need to tie the user to their post but 'author' is not included in the fields of the video upload form so I can't access the field when I save the form. When I add 'author' to the fields it gives a drop down box. (users shouldn't be able to post as anyone but themselves) I tried just listing the fields individually like so {{form.title}} to keep the author field but not show it to the user, it showed anyway. In the 'author' field of the VideoPost model I've tried changing out the null=True for these variants on default default=None, default=0, default='None', default=User, default=User.id where User = get_user_model() When I used default='None' the author dropdown box had the current users name in it, but still allowed a choice, when I tried to post it I got ValueError: invalid literal for int() with base 10: 'None' Also, in the views.py, I tried form = VideoPostForm(request.user,request.POST or None, request.FILES or None) and got CustomUser object has no .get() attribute and that was caused by form.save() I feel like this might be obvious to someone else but I've been staring at this code for a while now to figure it out.(a couple … -
Store extra information for product before adding to cart
tl;dr How do I change the context passed by the "Add to cart" button to add a different model instance that's a combination of that product and other information? I'm selling glasses, so while we have the product detail page showing the frame and frame variant (varying by color and size) information, the customer needs to also fill out a form for what type of lenses they want to get with that frame. One option could be to store each permutation of a frame variant and lenses combination as a frame variant in the database, like different storage options for smartphones, but I don't think that would be a good idea because: there are dozens of possible lens options the available lenses are essentially independent of the frame chosen it would be difficult to store information for the stock of frame variants if we only have frame variant + lenses objects. (I'm using the Django Shop 1.1, which adds managing stock.) Instead, I'm thinking of having a Glasses model with foreign keys to a frame variant and lenses, and this is what would be added to the cart. class Lenses(models.Model): material = models.CharField(choices=...) anti_reflective = models.CharField(choices=...) // ... class Glasses(models.Model): … -
calling opencv function on a django model object returning a TypeError?
I have a django project where users can upload images and these images can be processed by a function (made of some opencv functions). I want to save both the uploaded and the processed in a model.The processing function is called main. I tried using the function by running main(path_to_image.png) and it worked fine. so I tried doing this : models.py class UploadedImages(models.Model): patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images') pre_analysed = models.FileField(upload_to = user_directory_path , verbose_name = 'Image') processed_image = models.ImageField(upload_to = user_directory_path ,blank=True, verbose_name = 'Image') views.py def AnalyseView(request,pk=None): patient = get_object_or_404(Patient,pk=pk) if request.method == 'POST': form = forms.ImageForm(request.POST,request.FILES) if form.is_valid(): image = form.save(commit=False) image.patient = patient image.processed_image= main(image.pre_analysed) messages.success(request,"image added successfully!") image.save() return HttpResponseRedirect(reverse_lazy('patients:patient_detail', kwargs={'pk' : image.patient.pk})) else: form = forms.ImageForm() return render(request, 'patients/analyse.html', {'form': form}) else: form = forms.ImageForm() return render(request, 'patients/analyse.html', {'form': form}) The error I get bad argument type for built-in operation -
How to calculate exact age from database birthday field and date.today()?
I have two dates 1. quarry set from database which includes date field (1992-11-15) 2. and a date.today() How can I subtract them to get exact age? Thanks a lot -
Ajax Request sometimes causes `XHR failed loading: POST` error
I am trying to run a simple Ajax Request to pass a JSON object from my Javascript file to my Python file in Django. However half the time, I get the error XHR failed loading: POST when I run it as follows: var csrf = $("[name=csrfmiddlewaretoken]").val() $.ajax({ type: "POST", url: "/fridge", data: { "fridgeitems": JSON.stringify(fridge), "csrfmiddlewaretoken": csrf }, dataType: "json", success: function(data) { console.log(data.data); }, }) In my python file: fridgeitems = request.POST['fridgeitems'] # do something with the data response_data = json.dumps(fridgeitems) return JsonResponse({"Success": True, "data": {"fridge": fridgeitems}}) The data I am trying to pass to my python file (fridgeitems) is a list. I am unsure what is wrong because the error doesn't happen all the time so please can someone tell me how to fix it. -
Django: Create profile page creates everything except Multiple Choice Field in the database
I am using the same form for profile_edit and create_profile functionality. It is updating the multi-choice values in the profile_edit page but does not create in create_profile. Below is the form code in forms.py class ProfileForm(ModelForm): full_name = forms.CharField(required=True) current_position = forms.CharField(required=True) about_me = forms.Textarea(attrs={'required':True}) topic_name = forms.ModelMultipleChoiceField(Topic.objects.all()) class Meta: model = Profile fields =( "full_name", "current_position", "about_me", "topic_name", ) Below is the views.py for profile creation def create_profile(request, user_id): if request.method == "POST": form = ProfileForm(request.POST) if form.is_valid(): form = form.save(commit=False) user = get_object_or_404(User, id=user_id) form.user = user print(form.topic_name.all()) # Prints empty queryset form.save() return redirect("profile_view", user_id=user_id) else: context = {"form": form} return render(request, "profile/create_profile.html", context) else: form = ProfileForm() context = { "form": form } return render(request, "profile/create_profile.html", context) Below is Model.py class Topic(models.Model): topic = models.CharField(max_length=12) def __str__(self): return self.topic class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True,) full_name = models.CharField(max_length=60, null=True) current_position = models.CharField(max_length=64, null=True) about_me = models.TextField(max_length=255, null=True) topic_name = models.ManyToManyField(Topic) def __str__(self): return self.full_name Both create_profile and edit_profile templates are exactly the same. It saves everything except Multichoice field. -
Make Django accept url with infinite parameters
I want to make Django accept url that consists of infinite number of parameters. Something like dropbox has going on. Each parameter for each folder the file is in. There could be infinite number of subfolders. Parameter is alphanumeric. -
how to make a register page accept only one email address
i just want to know how to make a register page accept one email address i have not tried anything yet def register(request): enter code hereif request.method == 'POST': enter code hereform = UserRegisterForm(request.POST) enter code hereif form.is_valid(): enter code hereform.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) I want the register page to accept only one email address so it is used only once to register -
How to fix django-markdown issue in django-admin form
I'm making Blog app in Django and want to add Django-Markdown Field in Admin site for Posts model which holds data for blog posts. Which changings I have to need to do in the following code? I am using Django:2.2.4 and Django-Markdown-App: 0.9.6 Here is my Post Model ONE = 1 TWO = 2 status_choices = ( (ONE, 'draft'), (TWO, 'published') ) class Posts(models.Model): title = models.CharField(max_length=255, blank=False) content = MarkdownField() created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) author = models.ForeignKey( User, on_delete=models.CASCADE ) status = models.IntegerField(choices=status_choices, default=ONE) slug = models.SlugField(max_length=255) def __str__(self): return self.title class Meta: verbose_name = "Post" verbose_name_plural = "Posts" Here is admin.py code from django.contrib import admin from .models import Posts from django_markdown.admin import MarkdownModelAdmin # Register your models here. class PostsAdmin(MarkdownModelAdmin): prepopulated_fields = {'slug': ('title',)} admin.site.register(Posts, PostsAdmin) Here is settings.py INSTALLED_APPS = [ ......, 'django_markdown', ......, ] MARKDOWN_EDITOR_SKIN = 'markitup' Here is Project level urls.py urlpatterns = [ ....... path('markdown/', include('django_markdown.urls')), ....... ] I am expecting to display a markdown interface in the admin site instead of a simple text field, but the current output is a simple text field. -
In Django, how can I easily inherit a field and create a new class with this field preconfigured parameters?
I am currently using UUID in my PostgreSQL database, therefore I am also using PrimaryKeyRelatedField() with some parameters in order to avoid problems when encoding to JSON the UUID field. My serializer field looks like: id = serializers.PrimaryKeyRelatedField(read_only=True, allow_null=False, pk_field=serializers.UUIDField(format='hex_verbose')) And in every serializer that uses UUID I am having to use that. My question is, how can I create a new class based on PrimaryKeyRelatedField so that I don't have to write all those parameters (read_only, allow_null...) ? I am looking for something like: id = BaseUUIDField() Thanks -
How can I override a method in python open-id package using django?
I used mozilla-django-oidc for my sso. Everything is okay but the problem is, I'm using keycloak auth for my open-id. This mozilla oidc package has only allowed that individual users who has an email address, only then it will be verified claim. But, in my keycloak I've not kept any user email address, it's optional, for this reason, the user having no email address, creates this error after redirection: failed to get or create user: Claims verification failed but if the user has email, then it's working fine. After reading their documentation I've understood that I've to override this method probably: def verify_claims(self, claims): """Verify the provided claims to decide if authentication should be allowed.""" # Verify claims required by default configuration scopes = self.get_settings('OIDC_RP_SCOPES', 'openid email') if 'email' in scopes.split(): return 'email' in claims LOGGER.warning('Custom OIDC_RP_SCOPES defined. ' 'You need to override `verify_claims` for custom claims verification.') return True i want to keep only custom scope here like this: OIDC_RP_SCOPES = 'openid' but for this I've to override the verify_claims method. But my problem is that where should I call this override function? will this be in my settings.py or it'll be in my views.py? This is how I … -
Customer viewer count doubles once I refresh my django webpage
I am new to Django and I tried implementing a viewer count functionality on a website i'm working on. It seemed to be working well at first but i realised that when i refreshed a page the count added twice as opposed to once. What might be the problem? I am using class based views. class IdeaDetailView(DetailView): model = Ideas template_name = 'strathideasapp/ideas_detail.html' def get_object(self): object = super(IdeaDetailView, self).get_object() object.view_count += 1 object.save() return object -
How to Serve Django Applications with Apache2
I want to serve my Django applications with Apache2 over HTTPS. However, I am very new to server development and have never worked with Apache before. I have started a basic configuration file, but I am unsure as to what I am missing or incorrectly configuring. When I try to access my site over HTTPS I receive the following error: You're accessing the development server over HTTPS, but it only supports HTTP.. I have placed my certificate and certificate chain files at /etc/ssl/certs/ and my private key at /etc/ssl/private/. Please let me know if any other information is needed. Any help is greatly appreciated. 000-default.conf <VirtualHost *:443> ServerName www.my_domain.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SSLEngine on SSLCertificateFile /etc/ssl/certs/_.certificate.csr SSLCertificateKeyFile /etc/ssl/private/_.privatekey.key SSLCertificateChainFile /etc/ssl/certs/certificatechain.csr Alias /static/ /home/user/myproject/static <Directory /home/user/development/mysite/mysite/static> Require all granted </Directory> <Directory /home/user/development/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite python-path=/home/user/myproject python-home=/home/user/development/venv WSGIProcessGroup mysite WSGIScriptAlias / /home/user/development/mysite/mysite/wsgi.py </VirtualHost>