Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying videos in Django Template: Media Link
Currently trying to pull a video from a model, however it appears to be unable to locate the correct url by adding the media directory to the front of the pulled URL. Am I pulling the url from the model correctly? Code + Generated HTML + Console log -
IntegrityError at /signup-login/ duplicate key value violates unique constraint sts
i am getting this "duplicate key value violates unique constraint "myblog_profile_email_3f46e9ef_uniq" DETAIL: Key (email)=() already exists." error every time when i submit my signup form even with new email address.values save inside User table but it not redirect it on home page. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) first_name=models.CharField(max_length=50,blank=True) last_name=models.CharField(max_length=50,blank=True) email=models.EmailField(max_length=120) bio=models.TextField(blank=True) gender_choices=(('M','Male'),('F','Female'),('S','Special')) gender=models.CharField(max_length=1,choices=gender_choices,default='M') age=models.PositiveIntegerField(default=12) def __str__(self): msg = "Name : {0} {1}|| Email : {2} || gender : {3}".format(self.first_name,self.last_name,self.email,self.gender) return msg @receiver(post_save, sender=User) def ensure_profile_exists(sender, **kwargs): if kwargs.get('created', False): Profile.objects.get_or_create(user=kwargs.get('instance')) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): # first_name=forms.CharField(max_length=40,help_text="first Name") # last_name=forms.CharField(max_length=40,help_text="first Name") email=forms.EmailField(max_length=120) class Meta: model=User fields=('username','email','password1','password2') views.py from django.shortcuts import render from .forms import SignUpForm from django.shortcuts import redirect from django.contrib.auth import login,authenticate from .models import Profile # Create your views here. def index(request): return render(request,'myblog/home.html') def signUp(request): form=SignUpForm(request.POST) if form.is_valid(): user=form.save() user.refresh_from_db() # user.profile.first_name=form.cleaned_data.get('first_name') # user.profile.lastname=form.cleaned_data.get('last_name') user.profile.email=form.cleaned_data.get('email') user.save() username=form.cleaned_data.get('username') password=form.cleaned_data.get('password1') user=authenticate(username=username,password=password) login(request,user) return redirect('http://127.0.0.1:8000/') else: print('form not submitted successfully \n') form=SignUpForm() return render(request,'myblog/signup.html',{'form':form}) i am new please also help me to explain why thanks in advance -
How to upload and save image and form using django and ajax bootstrap modals?
How to upload and save image and form using django and ajax bootstrap modals I am trying to save an image and form using Django and ajax. When try to save it don't save, and i don't know why. some one can help me why is the reason. I want to save image and form but when i try it to do it and nothing is wrong and i don't know why. so i need to save the image with the form Views.py: def save_all(request,form,template_name): #function save articles data = dict() if request.method == 'POST': form = ArticlesForm(request.POST, request.FILES) if form.is_valid(): form.save() data['form_is_valid'] = True article = Articles.objects.all() data['feed'] = render_to_string('inventory/list_feed.html',{'article':article}) else: data['form_is_valid'] = False context = { 'form':form } data['html_form'] = render_to_string(template_name,context,request=request) return JsonResponse(data) def create_article(request): #function add articles if request.method == 'POST': form = ArticlesForm(request.POST, request.FILES) else: form = ArticlesForm() return save_all(request,form,'inventory/create_article.html') forms.py: #Django from django.contrib.auth.models import User from django import forms #models from inventory.models import Articles class ArticlesForm(forms.ModelForm): #Article Form class Meta(): model = Articles fields = ( 'name','quantity', 'fk_brand','model','fk_category', 'coust_buy','fk_supplier','userful_life','actual_state', 'date_check','fk_user','fk_microbusiness','location','img', 'description') labels = { 'name':'','quantity':'', 'fk_brand':'','model':'','fk_category':'', 'coust_buy':'','fk_supplier':'','userful_life':'','actual_state':'', 'date_check':'','fk_user':'','fk_microbusiness':'','location':'','img':'', 'description':'',} widgets = { 'img': forms.FileInput(attrs={'type': 'file'}), } models.py: class Articles(models.Model): #models article Nuevo = 'Nuevo_1' Semi_nuevo … -
django dictionary of querysets
i made i dictionary of querysets in one of my views : list =[] while(x<100 and i>0): order_qs_1 = Order.objects.filter(timestamp__range=[start_date, end_date]) x = x+1 i=i-j list.append(order_qs_1) context= { 'list':list, } but now i don't know how to access the data inside the dictionary in my template in my template i did something like this : {% for item in list %} {{ item }} </br> {% endfor %} this is what it renders: the random numbers and characters are the order_id in my order model the queryet is a list of orders coming from my order model but this not what i want , i want the access the data inside each queryset -
Django , form rendered twice. User is created without profile. Best practice to process multiple related forms in a single view?
I have 4 separate forms being processed in the same view. 3 of the forms' models are dependent on the 4th. They essential extend a User object When trying to save, I get the following error: no such table: WAD2app_userprofile' In the log I get: <UserProfile: UserProfile object (None)> profile_form <UserProfileForm bound=True, valid=True, fields=(image;postcode;building;address;phone)> and all the other forms are also valid and bound. view registered = False if request.user.is_authenticated: return redirect('WAD2app:profile') if request.method == 'POST': user_form = UserForm(request.POST) profile_form = UserProfileForm(request.POST) preference_form = UserPrefForm(request.POST) life_form = UserLifeForm(request.POST) if user_form.is_valid() and profile_form.is_valid() and preference_form.is_valid() and life_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() #prevents DB integrity errors profile = profile_form.save(commit=False) profile.user = user if 'picture' in request.FILES: profile.picture = request.FILES['picture'] profile.save() pref = preference_form.save(commit=False) pref.user = user pref.save() life = life_form.save() life.user = user life.save() dogs = Dog.objects.all() calcNewUser(user, dogs, True) registered = True messages.success(request, 'Your account has been successfully created! ') return redirect('WAD2app:login') else: print(user_form.errors, profile_form.errors) messages.error(request, 'Something went wrong while trying to register your account. Please try again.') else: user_form = UserForm() profile_form = UserProfileForm() preference_form = UserPrefForm() life_form = UserLifeForm() return render(request, 'wad2App/users/register.html', context = {'user_form': user_form, 'profile_form': profile_form, 'preference_form': preference_form, 'life_form': life_form,'registered': registered}) models class UserProfile(models.Model): user = … -
is there a way to represent several models in a single page?
I am a beginner in django and I am stuck in a small problem, I hope to be able to find help: I have 03 models class ModelA (models.Model): id = models.UUIDfield (primary_key = True, .......) ........ other attributes ....... class ModelB (models.Model): id = models.AutoField (primary_key = True) medelA = models.OneToOneFields ('ModelA', on_delete = models.CASCADE) class ModelC (models.Model): id = models.AutoField (primary_key = True) medelB = models.ForeignKey ('modelB', on_delete = models.CASCADE) I want to put the 03 models in the same pages and I have a problem of passing keys between the forms Thanks for your help -
Using FontAwesome5 in Django
I am using FontAwesome5 in Django. But when I render the html using icon.as_html I only get the icon. <i class="fas fa-hands-helping " aria-hidden="true"></i> Is there a way to add fa-stack-1x fa-inverse? -
How do I connect this JS form that gets the data and push it to my django.view file
I've been struggling for hours to get this java script code data from here to my django.view, I changed the URL but it's still trying to find an original php file '././mail/contact_me.php'. Can anyone let me know how I can do this, I want it to go into the view so then I can feed the data into a django model and then manage it from there, that way I am using the framework in something I know better as javascript is new to me and is very confusing, however if you guys have more effective recommendations I am all ears $(function() { $("#contactForm input,#contactForm textarea").jqBootstrapValidation({ preventSubmit: true, submitError: function($form, event, errors) { // additional error messages or events }, submitSuccess: function($form, event) { event.preventDefault(); // prevent default submit behaviour // get values from FORM var name = $("input#name").val(); var email = $("input#email").val(); var phone = $("input#phone").val(); var message = $("textarea#message").val(); var firstName = name; // For Success/Failure Message // Check for white space in name for Success/Fail message if (firstName.indexOf(' ') >= 0) { firstName = name.split(' ').slice(0, -1).join(' '); } $this = $("#sendMessageButton"); $this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages … -
Python await outside async function
I'm trying to send data to my client from a Django channels consumer. I tried the following code: class EchoConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.send_json('test') var = '' def process_message(message): JSON1 = json.dumps(message) JSON2 = json.loads(JSON1) #define variables Rate = JSON2['p'] Quantity = JSON2['q'] Symbol = JSON2['s'] Order = JSON2['m'] print(Rate) await self.send_json(Rate) bm = BinanceSocketManager(client) bm.start_trade_socket('BNBBTC', process_message) bm.start() The problem with my actual code is that i'm getting the following error: SyntaxError: 'await' outside async function I think this happens because i'm using await inside a synchronous function. The problem is that i don't know how to send the variable Rate in any other way. Can someone help me fix this issue? -
Django classmethod doesn't have a decorator
I saw a couple of classmethod that doesn't have a decorator @classmethod. What's the reason about it? https://github.com/django/django/blob/3.0/django/db/models/base.py#L320 https://github.com/django/django/blob/3.0/django/db/models/manager.py#L20 -
How do I display my static files in my html from django
I have created my static folder and uploaded images into my images folder. The local server runs alright but the image is not able to display when i call the path to it in http://127.0.0.1.8000/static/images/theimage.jpg -
SuspiciousFileOperation at /media/C:/fakepath/example.png when submit from angular
I'm building an Angular + Django project, where the user can upload a file to a model: Model: def upload_path(instance, filename): return '/'.join(['files', str(instance.titulo), filename]) class File(models.Model): titulo = models.CharField(max_length=154, null=False, blank=False) file = models.FileField(upload_to=upload_path, null=False) When I send a post request through Insomnia , everything is Ok, the file is saved in the media root(media), but when I send through Angular the path that it saves is similar to the title, and that errors occurs. Angular: <div class="row"> <label style="margin-left: 10px;">Anexos</label> <label id="label-input"> <input [(ngModel)]="ticket.file" type="file" single id="input-file"> </label> </div> Services: htttpHeaders = new HttpHeaders().set("Content-Type", "application/json").set('Authorization', this.token); public saveNewTicket(ticket): Observable<any> { return this.http.post(this.baseUrl + "ticket/", ticket, { headers: this.htttpHeaders }); } -
Django CMS: How to avoid SITE_ID to be set in settings?
We are using Django CMS for a while, and need to migrate our website to a multi-site implementation with Django Sites framework. We wanna use CurrentSiteMiddleware to detect which site is used (based on subdomain). In result we will have a request.site.id set by middleware that is based on the current user request to our website. I've tried to find the best way how to use Django CMS without forking it, and didn't find a good way how to do this. What do we actually need: each Page can be used on the current Site, or on few sites at the same time. To do so, Django documentation recommends to add M2M FK to the Site model from each Article object (in our case, it's the Page object). But the TreeNode has the FK to the Site model, that means that only one Page can be mapped to a single site. But we need to map one Page to one of few sites at the same time. we want to use Django Sites framework, because Django has it built-in and creators of Django use it on their projects (and it's for what is was designed - to map some object … -
Django creating a relation between 2 models manually seems impossible
I want to enable my users to add bookmarks for Posts and other elements to there account but sadly each time I check if there is already a Boomark present for a specific element I get back the following error: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. which again makes absolut zero sense to me as I manually set the relation exactly as desicbed here: https://docs.djangoproject.com/en/3.0/ref/contrib/contenttypes/#reverse-generic-relations I already ask this question several times at various forums and collegues but sadly nobody seems to understand the problem so far. I would really appreciate it if smb. has a good hint here as I got absolut stuck with this. Im on Django 3.0.4 and Python 3.8.2. models.py of App1 from App2 import UserBookmarks class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Title", max_length=20) content = models.TextField(verbose_name="Post Content", max_length=2000) ... bookmarks = GenericRelation(UserBookmarks, related_query_name='post') models.py of App2 bookmarkable_models = models.Q(app_label='App', model='post') | models.Q(app_label='App', model='model-b') | models.Q(app_label='App', model='model-c') class UserBookmarks(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) content_type = models.ForeignKey(ContentType, limit_choices_to=bookmarkable_models, on_delete=models.CASCADE, null=True, blank=False) object_id = … -
django framework mp3 audio file
i am making a website with a list of mp3 files and i want a detail view. the problem is django cannot find the mp3 file. it shows up in the source code and the audio bar shows up so i can play/pause adjust volume etc in download.html u see i use {{ object.file.url }} in a h1 tag, the url is right but django gives me a 404 error Gives a 404 error in the console. in html it also does not wrok because i use need a content object. i want the url to be http://example.com/download/(id) then the download.html shows and they can play the mp3 file or download it download.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Download</title> </head> <body> <audio controls> <source src="{{ object.file.url }}" type="audio/mpeg"> Your browser does not support audio </audio> <h1>{{ object.file.url }}</h1> </body> </html> views.py from django.shortcuts import render, get_object_or_404, reverse from .models import Song def index_view(request): queryset = Song.objects.all() context = { 'list': queryset } return render(request, 'index.html', context) def download_view(request, id): obj = get_object_or_404(Song, id=id) context = { 'object': obj, } return render(request, 'download.html', context) setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages', ] MIDDLEWARE = [ … -
Django Rest API for models with "optional" Foreign Key
I have a model: models.py class Doctor(models.Model): doctor_name = models.CharField(max_length=264, unique=True) # on_delete argument needs to be researched more deeply. address = models.ForeignKey(Address, on_delete=models.CASCADE, null=True, blank=True) contact_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") contact = models.CharField(validators=[contact_regex], max_length=15, null=True, blank=True) # validators should be a list qualifications = models.CharField(max_length=264, null=True, blank=True) license = models.CharField(max_length=264, null=True, blank=True) note = models.TextField(null=True, blank=True) def __str__(self): return self.doctor_name In this model "address" foreign-key field is optional. I want to create a rest API. But if I do not provide address fields, it gives the error. It works fine if I provide address fields. serializers.py class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = '__all__' class DoctorSerializer(serializers.ModelSerializer): address = AddressSerializer() class Meta: model = Doctor fields = ['doctor_name', 'contact', 'qualifications', 'license', 'note', 'address'] def create(self, validated_data): address_data = validated_data.pop('address') addr = Address.objects.create(**address_data) print(addr) doctor = Doctor.objects.create(**validated_data, address=addr) return doctor -
Using an annotation value in subsequent annotation throws FieldError
What I am trying to do: I have models Topic and Entry. Entry has a ForeignKey to topic. I need to list topics on condition that the user has entries in it (created in last 24 hours). I also need to annotate count, it needs to be the total number of entries created after the last entry written by the user. (To put it more thoroughly, you can think of an inbox where you have list of conversations with number of unread messages.) This's what I have come up with: relevant_topics = ( Entry.objects.filter(author=user, date_created__gte=time_threshold(hours=24)) .values_list("topic__pk", flat=True) .order_by() .distinct() ) qs = ( Topic.objects.filter(pk__in=relevant_topics).annotate( latest=Max("entries__date_created", filter=Q(entries__author=user)), count=Count("entries", filter=Q(date_created__gte=F("latest__date_created"))), ) ).values("title", "count") Which will throw: FieldError: Cannot resolve keyword 'date_created' into field. Join on 'latest' not permitted. I don't really know if Django itself doesn't support what I've written, or my solution is faulty. I thought adding count using .extra(), but I couldn't figure out how to use latest annotation there. I would really appreciate any query that produces the expected output. -
Django - email fields not listed after the call of .super().clean()
I'm new to Django and my apologies if this is to basic question (or mistake), but I'm having issues with email format validation when the email is typed like: test@com. I created the form.py and views.py below for test: form.py from django import forms from django.core import validators class userForm(forms.Form): fname = forms.CharField(label="First name") lname = forms.CharField(label="Last name") email = forms.EmailField(label="Email") vemail = forms.EmailField(label="Email validation") def clean(self): all_clean_data = super().clean() fname = all_clean_data['fname'].lower().capitalize() lname = all_clean_data['lname'].lower().capitalize() email = all_clean_data['email'].lower() vmail = all_clean_data['vemail'].lower() if email != vmail: raise forms.ValidationError("Email address doesn't match, please try again") views.py def users(request): form = forms.userForm() if request.method == 'POST': form = forms.userForm(request.POST) if form.is_valid(): print('Validation ok') return render(request,"test_app/users.html",{'formName':form}) Seems that everything is working fine ... but ... if in the form (webpage) I type an email address like: test@com and submit the form, 2 things happens: I do not get an alert like "Invalid email format" on the form (webpage) The email "key" on all_clean_data['email'] does not exists. If I type a valid email like: test@test.com, it works. If I type an invalid email address like: abcde, then I get an alert message. The issue is when I type things like: test@com ... then I … -
django website hangs in production apache+mod_wsgi+django
I'm deploying my first website with django. I've followed a lot of tutorials and documentations and now I'm stucked since I don't even know how to get information about the error. Please help me. SO: Centos7 python 3.7.6 apache 2.4.6 django 3.0.3 I developed the site with the development server and all works completely fine, no errors at all. This is my 'real project'. Installed httpd, and configured the firewall, allrighty the testing 123... page was shown. Then I followed the documentation about mod_wsgi to install it and deploy a 'hello world' web page as the docs sugested, everything worked all right. A blank page with 'Hello world' appeared. Then I prepared a 'new project' with django which worked fine with development server.(no surprise). Afterwards the 'new project' worked properly when using apache+mod_wsgi, I am able to access the admin site. Then I thought I would be able to deploy the website I developed before just edited the the same django.conf that I used with the 'new project' to pointing to the path of my 'real project'. But it didn't work. It just hangs till times out; it does nothing. I have no other website or similar so I didn't … -
No module named 'django' in standalone Django App
I have installed Django on Windows 10, Django Version 3, Python 3.8 from Conda, with env, on VS Code My Django works fine without any problem and my App and Project also works fine, but I decided to use Faker to generate some fake data in my DB, I have to mention that my Model works and connected successfully to my DB and migration process was successful without any problem. I write this Standalone app for Faker to run it whenever I need manually: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') import django django.setup() # Implement Fake Population script here. import random from first_app.models import AccessRecord, Topic, Webpage from faker import Faker fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range (N): # Get the topic for the entry top = add_topic() # Create the fake data for that entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # Create the new webpage entry webpg = Webpage.objects.get_or_create(topic=top,url=fake_url, name=fake_name)[0] # Create a fake access record for that webpage acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0] if __name__ == "__main__": print('Population Script!') populate(20) print('Population Completed!') But whenever I run this code, I get … -
Send json data to frontend in Django Channels
I have the following consumer: client = Client('', '') trades = client.get_recent_trades(symbol='BNBBTC') class EchoConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.send_json('test') def process_message(message): JSON1 = json.dumps(message) JSON2 = json.loads(JSON1) #define variables Rate = JSON2['p'] Quantity = JSON2['q'] Symbol = JSON2['s'] Order = JSON2['m'] print(Rate, Symbol) bm = BinanceSocketManager(client) bm.start_trade_socket('BNBBTC', process_message) bm.start() This consumer starts a websocket connection to a cryptocurrency exchange and retrieves some trades. With this code, i will see the trades appearing on my console, but i can't find a way to send them to my frontend. If i try await self.send_json('Test'), my frontend will receive the message, but i don't know how to send the trades that the websocket retrieves and prints to my console. I tried this: await self.send_json(Rate, Symbol) but that throws an await outside of async function error. Can someone help me fix this issue? Thanks in advance! -
Django: how to get Foreign key id?
I have 2 models as below class Product(models.Model): product_name = models.CharField(max_length=100) product_weight = models.CharField(max_length=30) class ProductImage(models.Model): product = ForeignKey(Product, on_delete=models.DO_NOTHING) How to extract product_id in ProductImage model? Thanks in advance. -
Auto save login user_id as a foreignkey using forrm.py in django
how to submit form which automatically take user_id of current active user as a Foreignkey with form.py file in django -
Django Template format date string
I have date fields in my content dictionary in ISO format ('Y-m-d') and want to display these fields using the "date" filter of Django Template but whenever I use the date filter the date is not displayed and without the date filter it is displayed. As per the documentation, the "date" filter requires datetime object for filtering. Is there any work around to apply the filter apart from changing the content before sending it to the template? -
name 'login' is not defined. python (django)
I have one problem, w want create user and after login. i create user but can't login. my error ---> name 'login' is not defined. from django.contrib.auth.views import login. I tried this too but it didn't work where do I have a problem and how can it be resolved? i couldn't find a way to solve the problem on Google. please help me, Thanks in advance. views.py from django.shortcuts import render from django.http import HttpResponse import datetime from django.contrib.auth import authenticate from home.forms import SignUp def regform(request): if request.method == 'POST': form = SignUp(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password1') user = authenticate(email=email, password=raw_password) login(request, user) return redirect('home') else: form = SignUp() return render(request, 'home/home.html', {'form': form}) models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ from django import forms class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and …