Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
my audio starts again on changing it's current time
I wanted to make an audio information bank and also an audio player. because of knowing the only backend Django. I made it in Django. first I made the information bank and I was happy about it. Then I made the player recently and add it to the backend setting. But there was a problem. when I made the player I manually put an mp3 file in audio src. And It just worked fine. But When I tried it dynamically by filtering with the 'get' request and return it in the dictionary. But in that, The problem started coming. some audio played perfectly but some also played but on changing the current Time via keyboard or the seeker the audio returned at the start. How did it happen? It only caused on the dynamic audio player but when I put a song manually it worked. What is the problem? I am definitely sure that no problem on server backend or static file management because On manual song it works. It is something problem on js. And not also a problem for being on a different browser. Because I tried all browsers. It will be most helpful If anyone gives the … -
Could I Please Have some advice on how to structure my database?
So basically I'm developing a price comparison site and I'm wondering if there are any flaws in my Database design. The User can only have one Basket. The Basket can have many products. A product can have many retailers. A product can only have one price history graph (values calculated from the average). A user can scrape many custom products which will also be stored in a table. The reason why I am storing the Basket in the backend and not the frontend, is because one of my scripts will compare the current price of each retailer for a certain product to the alert price and will send the user an email if it meets those requirements. Thanks -
Save/Reference multiple values in cell of database table
I am working on a E-commerce website side project. And I need some help in saving data related to Product in Database table. Requirement - A product can have different sizes available and color available. Product A - Size - S,M,X,XL and color - Blue, Black, White Product A - Size - S,M and color - Pink, Red, Orange Now how can I save Size and color in database for each product. Could anyone please advice? -
cannot fork beacause you own this repository and not member of any organisations when try to fork a repository in git hub
I got the messege cannot fork because you own this repository -
How to access multiple file field in template
I have build a WebApp that users can upload multiple images with a Post. I followed This tutorial BUT now i have no idea how to access multiple file fields in template. class Story(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default='',null=True) image = models.FileField(blank=True,null=True) class ImgModel(models.Model): story = models.ForeignKey(Story,default=None,on_delete=models.CASCADE) img = models.FileField(upload_to='status',null=True) admin.py class StoryImageAdmin(admin.StackedInline): model = ImgModel @admin.register(Story) class StoryAdmin(admin.ModelAdmin): inlines = [StoryImageAdmin] class Meta: model = Story @admin.register(ImgModel) class StoryImageAdmin(admin.ModelAdmin): pass I have no idea how to access multiple filefields in template. Any help would be Appreciated. Thank you in Advance. -
No module named django.contrib.auth.hashers
I am making a User Registration and Login website, wherein I am using Django. I have already executed pip install django[argon2] but the error No module named 'django.contrib.auth.hashers.Argon2PasswordHasherdjango'; 'django.contrib.auth.hashers' is not a package keeps on coming. settings.py """ Django settings for User_Authentication project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, "templates") STATIC_DIR = os.path.join(BASE_DIR, "static") MEDIA_DIR = os.path.join(BASE_DIR, "media") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ')o5ax4nab1hip&ef6z^g_19if25lexbpzf=vks&6s#lwi!wx_(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'basic_app' ] 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 = 'User_Authentication.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], '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 = 'User_Authentication.wsgi.application' # Database # … -
how to use csrf token in Django integrated with vuejs using Django webpack loader?
I am using Vuejs as frontend and Django rest framework as backend, I have some confusions how to use csrf token, my question has 2 part, first I write my configurations. first as Django documentation stated, "If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie()", so this is my view that renders the page which loads webpack bundles. @ensure_csrf_cookie def main_view(request): return render(request, 'index.html') and again as Django documentation I used below configuration to send csrf token along with Axios request. function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); //axios request async createFromCSV(token, data) { const options = … -
Can't override django oscar's styles.css
I'm trying to override oscar's styles.css file in order to change the color of navbar but it doesn't work. I'm using oscar version 1.6 python 3.6.0 and django 2.0. I forked oscar's statics with python manage.py oscar_fork_statics enter image description here enter image description here When I save the color changes for .navbar-inverse and run the server, nothing changes. Can you help? -
django.db.utils.ProgrammingError: relation "masters_user" already exists
I was trying to solve something min my db and mistakenly deleted the django_migrations table. Now when I run the migrate command it says: django.db.utils.ProgrammingError: relation "masters_user" already exists How can I solve this without dropping the entire Database? -
Django raw query gives none value
I have a questionnaire. I like to get the value of a row with raw query but when I loop through in my HTML file it gives me just the first value but the rest 11 gives me none so my addition oft the values also gives me none. I can't understand what am I doing wrong. I made this operation many before on the same way and worked great. I have 12 questions that I made with html input (not Django forms) for certain reasons, but it works well and it posts the values to the database where I have all the positive and negative values. models.py class Vezetoi(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) vezetoi_v01 = models.IntegerField( null=True) vezetoi_v02 = models.IntegerField( null=True) vezetoi_v03 = models.IntegerField( null=True) vezetoi_v04 = models.IntegerField( null=True) vezetoi_v05 = models.IntegerField( null=True) vezetoi_v06 = models.IntegerField( null=True) vezetoi_v07 = models.IntegerField( null=True) vezetoi_v08 = models.IntegerField( null=True) vezetoi_v09 = models.IntegerField( null=True) vezetoi_v10 = models.IntegerField( null=True) vezetoi_v11 = models.IntegerField( null=True) vezetoi_v12 = models.IntegerField( null=True) forms.py class VezetoiForm(forms.ModelForm): class Meta: model = Vezetoi fields = ['vezetoi_v01', 'vezetoi_v02', 'vezetoi_v03', 'vezetoi_v04', 'vezetoi_v05', 'vezetoi_v06', 'vezetoi_v07', 'vezetoi_v08', 'vezetoi_v09', 'vezetoi_v10', 'vezetoi_v11', 'vezetoi_v12' ] views.py - I didn't copied some parts here that are … -
tags for google search in djnago
How can i make tags for google search to my domain name for example this is the domain name: www.BuildSoftApp.ir when some one search like, build soft or make app and etc google find this domain name, in word press when we making a page there is an option for add tags for search engines, i don't know how can i do this in django or it is possible or not, if there is a way to do this please tell me. -
Getting a RelatedObjectDoesNotExist error in Django, would like to make new Object if one does not exist
If I get this RelatedObjectDoesNotExist error, and I want to work around it, I would like to make some "if" statement that produces those related objects in the database so they can exist if they didn't before. In my model: user = models.OneToOneField( User, null=True, on_delete=models.CASCADE) var_1 = models.PositiveIntegerField(validators=[MaxValueValidator( 2000), MinValueValidator(50)], null=True, blank=False) var_2 = models.PositiveIntegerField(validators=[MaxValueValidator( 2000), MinValueValidator(50)], null=True, blank=False) var_3 = models.PositiveIntegerField(null=True, blank=False) var_4 = models.CharField(max_length=254, null=True, blank=True) var_5 = models.CharField(max_length=254, null=True, blank=True) So, the user does exist, but the var_1 - 5 do not. But, they will need those eventually (especially to view the page I am accessing). Therefore, if they access that page, I just want to create those variables in their database attached to their username. I hope this is enough information for this. I am very new to Django and I am finding all the different models/views etc a little confusing. -
In a django project, what all files am I supposed to add in .gitignore?
I am making a Django website project. I decided to push it to my git repo but I am not sure what files I should add in .gitignore I guess all the settings.py files are certainly not supposed to be committed to git. What other files should I ignore? -
Django + React how many requests are too many?
I am creating an app with react frontend and django rest framework backend. It will basically be a fancy form with which the user can create an "order" of many products. The backend has a database of around 10000 products which have the following formating: { "id": 1, "code": "1400", "height": 60, "width": 50 } Many of the products share the same code. There are roughly 20 unique code values equally divided among the whole. So roughly 500 products with each code. The frontend part of the app has a series of dependent dropdown lists that the user can use to specify a combination of code, height and width. The requirement is of course that the desired combination must be a valid one, meaning, it must represent an item that exists in the database. So if for example the user choses the code 1400 from the first dropdown list, the possible "select" values from the second dropdown list must be height values that correspond to items with the code 1400. The frontend uses axios get requests to fetch the data from the backend and then does the required calculations. The problem is, regarding design. How should I balance the amount … -
Why can't i see /Users/Evalyn/folder13/trydjango/src
Evalyns-iMac:trydjango Evalyn$ pwd /Users/Evalyn/folder13/trydjango Evalyns-iMac:trydjango Evalyn$ ls bin lib pyvenv.cfg src Evalyns-iMac:trydjango Evalyn$ pwd /Users/Evalyn/folder13/trydjango -
Get the following error while submitting a form: RelatedObjectDoesNotExist at /agents/create/ User has no userprofile
I'm working on a project and get the following error: RelatedObjectDoesNotExist at /agents/create/ User has no userprofile.I created a form for the user to submit an Agent but when I create an Agent using the form it gives me the above mentioned error but when I try to submit an already created agent it says User with that name already exists. Here is my code: views.py from django.shortcuts import reverse from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin from leads.models import Agent from .forms import CreateAgentForm class AgentListView(LoginRequiredMixin, generic.ListView): template_name = 'agents/agent_list.html' def get_queryset(self): return Agent.objects.all() class CreateAgentView(LoginRequiredMixin, generic.CreateView): template_name = 'agents/agent_create.html' form_class = CreateAgentForm def get_success_url(self): return reverse('agent-list') def form_valid(self, form): agent = form.save(commit=False) agent.userprofile = self.request.user.userprofile agent.save() return super(CreateAgentView, self).form_valid(form) models.py from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username class Lead(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) age = models.IntegerField(default=0) agent = models.ForeignKey('Agent', on_delete=models.CASCADE) def __str__(self): return f"{self.first_name} {self.last_name}" class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) def __str__(self): return self.user.first_name def post_user_profile(instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(post_user_profile, sender=User) urls.py from django.urls import path from .views import AgentListView, … -
Upload multiple images at same time
I have build a Story app, So users can post their stories ( like :- instagram stories ). BUT i am stuck on a Problem. What i am trying to do :- I am trying to build a feature so that Users can upload multiple images at the same time. models.py class ImgModel(models.Model): img = models.FileField(upload_to='status_images',null=True) def __str__(self): return f'[USER] {self.img} [img]' class Story(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default='',null=True) img = models.FileField(upload_to='status_images',null=True) def __str__(self): return f'[USER] {self.user}' views.py def new_image(request,pk): form = NewImageForm(request.POST,request.FILES) requested = request.user if request.method == 'POST': form = NewImageForm(request.POST,request.FILES) if form.is_valid(): new_video = form.save() new_video.user = request.user new_video.save() return redirect('stories') else: form = NewImageForm() context = {'image':image,'form':form,'requested':requested} return render(request, 'new_images.html', context) What have i tried :- I tried many answers like THIS and THIS but nothing worked for me. I also tried ManyToManyField but when i add images separately then it also asks for ManyToMany Field model to save data. I want to add images at same time and upload as stories. Any help would be Appreciated. Thank You in Advance. -
Django - inline formset data not saving with create view
I'm trying to save the ProjectPriority with the Project using the CreateView but can't get it to save. Theoretically it should save the ProjectPriority with the Project when creating a new Project. Models.py: class Project(models.Model): name = models.CharField(verbose_name="Name", max_length=100) details = models.TextField(verbose_name="Description", blank=False) priority = models.ManyToManyField( Priority, through='ProjectPriority', related_name='priority' ) creator = models.ForeignKey(User, on_delete=models.CASCADE) class ProjectPriority(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) priority = models.ForeignKey(Priority, on_delete=models.CASCADE) score = models.CharField(max_length=1000, choices=priority_choices) class Meta: verbose_name = "Priority" verbose_name_plural = "Priorities" Views.py: class ProjectCreateview(LoginRequiredMixin, CreateView): model = Project form_class = ProjectCreationForm success_url = '/' def get_context_data(self, **kwargs): ChildFormset = inlineformset_factory( Project, ProjectPriority, fields=('priority', 'score'), can_delete=False, extra=Priority.objects.count(), ) data = super().get_context_data(**kwargs) if self.request.POST: data['priorities'] = ChildFormset(self.request.POST) else: data['priorities'] = ChildFormset() return data def form_valid(self, form): form.instance.creator = self.request.user context = self.get_context_data() priorities = context["priorities"] self.object = form.save() if priorities.is_valid(): priorities.instance = self.object priorities.save() return super().form_valid(form) -
How to iterate through classes of file in python?
I have a file called models with few classes and I need to iterate throw them in order to get each class to preform the same task on it. my problem: from django.contrib import admin from . import models # this is very repetetive admin.site.register(models.Myclass) admin.site.register(models.MySecondclass) admin.site.register(models.MyThirdclass) #. #. #... my goal: from django.contrib import admin from . import models for class in models: admin.site.register(class) -
I created a django project. I make models and class and I have some html file also. I want to show 10 post in any categories. I cant write loop here [closed]
please send me easy way to run loop and show my post in categories. when I create post in admin panel my recent post will be show here. -
how to stop create view if already created django
please help me in making this application in django project Here is models.py file code from django.db import models from bio.models import Profile class Question(models.Model): name = models.TextField(max_length=500) def __str__(self): return self.name class Answer(models.Model): question = models.ForeignKey(Question, related_name='question', on_delete=models.CASCADE) profile = models.ForeignKey(Profile, related_name='profile', on_delete=models.CASCADE) text = models.TextField(max_length=400) created_on = models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return "{0} on {1}".format(self.question, self.profile) here is views.py file code class DetailViewMixin(object): details_model = None context_detail_object_name = None def get_context_data(self, **kwargs): context = super(DetailViewMixin, self).get_context_data(**kwargs) context[self.context_detail_object_name] = self.get_detail_object() return context def get_detail_object(self): return self.details_model._default_manager.get(pk=self.kwargs['pk']) class AnswerCreate(DetailViewMixin, CreateView): details_model = Question context_detail_object_name = 'question' model = Answer form_class = NewAnswerForm template_name = "qna/answer.html" success_url = reverse_lazy('qna:list') def form_valid(self, form): form.instance.profile_id = self.kwargs.get('pk') form.instance.question_id = self.kwargs.get('pk') return super().form_valid(form) here is my forms.py code from django import forms from .models import Answer class NewAnswerForm(forms.ModelForm): class Meta: model = Answer fields = ['text',] def clean(self): try: Answer.objects.get(text=self.cleaned_data['text'].lower()) raise forms.ValidationError('Answer exists!') except Answer.DoesNotExist: pass return self.cleaned_data where am I going wrong???? I want that if user answers one question then he couldn't answer it again how can i do form validation if object is already created -
How to repeatedly show additional forms / fields
We are new to Django / Python. We are trying to make a form which allows users to add their itineraries before submission. For example, whenever we press a "+" button, it will show an extra POIFormset models.py class PointOfInterest(models.Model): TYPES = ( ('Food','Food'), ('Sports', 'Sports'), ('Events', 'Events'), ('Accommodation','Accommodation'), ('Sight Seeing', 'Sight Seeing'), ('Shopping', 'Shopping'), ) name = models.CharField(max_length=100, null=True) #structued with google authentication poitype = models.CharField(max_length=100, null=True, choices=TYPES) timespent = models.PositiveIntegerField(null=True) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() # can use auto_now_add=True for current timep posted date_posted = models.DateTimeField(default=timezone.now) # if user is deleted, the post deleted as well, one-way street, not other way around author = models.ForeignKey(User, on_delete=models.CASCADE) travel_date_start = models.DateField(default=timezone.now, null=True) travel_date_end = models.DateField(default=timezone.now, null=True) poi = models.ManyToManyField(PointOfInterest) # poi = models.ForeignKey(POI, null=True, on_delete = models.SET_NULL) views.py def intinary(request): #formset PostForm = modelformset_factory(Post, fields = ('title', 'travel_date_start','travel_date_end','content', 'author')) POIFormset = modelformset_factory(PointOfInterest, fields =('name','poitype','timespent')) #base code if request.method == 'POST': post_form = PostForm(request.POST) poi_form = POIFormset(request.POST) if post_form.is_valid() and poi_form.is_valid(): post_form.save() poi_form.save() return redirect('blog-home') else: post_form = PostForm(queryset=PointOfInterest.objects.none()) poi_form = POIFormset(queryset=PointOfInterest.objects.none()) #base code context = { 'post_form': post_form, 'poi_form': poi_form, } return render(request, 'blog/frontend.html', context) Thanks guys -
checkboxes added dynamically with django
I am using formsets so add button adds the form but I want to remove them after the delete checkbox has been checked (where i need help), I dont understand much javascript. Here might be the answer but it does not work for me: Can't understand why this error(Uncaught TypeError: $(...).is(...).each is not a function) got on? when I try this code: $("input[class='remove-form']").click(function(){ var n = $( "input[type='checkbox']:checked" ).length; console.log('n here',n) $("input[type='checkbox']:checked").each(function(){ // $(this).parents('.form-row').remove(); console.log('removed'); }) }) only the first checkbox works(which wasn't added dynamically)(or in log case shows the number of boxes checked). The dynamically created checkboxes don't just show any response. The Form which will be appended: <div id="items-form-container" style="display: none;"> .... <div class="col-2"> <label>Delete</label> </div> <div class="col-4"> <div class="input-group"> <input type="checkbox" name="quizz_question-__prefix__-DELETE" class="remove-form" id="id_quizz_question-__prefix__-DELETE"> </div> </div> In short the dynamically added checkboxes doesn't work in my ajax function.Please HElp. -
how to change the user in model after completing wallet the process
new to Django, here is my model.py class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=25, null=True) phone = models.CharField(max_length=12, null=True) class Coin_info(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) coinid = models.CharField(max_length=255, null=True) digit = models.CharField(max_length=18, null=True) ctp = models.FloatField(max_length=100, null=True) transection_id = models.IntegerField(null=True, default=0) slug = models.SlugField(max_length=250, null=True, blank=True) date_created = models.DateField(auto_now_add=True, null=True) class Balance(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) balance = models.IntegerField(default=0) In view.py, when the customer is logged in, I want to change the user(owner) of Coin_info to the ownership of the sender(customer) and change the value of ctp configured. def buy_c(request, ok): ctp_val = Coin_info.objects.get(id=ok) msg = "Enter Details" if request.method == "POST": try: username = request.POST["username"] amount = request.POST["amount"] senderUser = User.objects.get(username=request.user.username) receiverrUser = User.objects.get(username=username) sender = Balance.objects.get(user=senderUser) receiverr = Balance.objects.get(user=receiverrUser) sender.balance = sender.balance - float(amount) receiverr.balance = receiverr.balance + float(amount) a = Coin_info.objects.change(user=senderUser) ##this is my silly try! if senderUser == receiverrUser: return Exception.with_traceback() else: a.save() sender.save() receiverr.save() msg = "Transaction Success" return redirect("/user") except Exception as e: print(e) msg = "Transaction Failure, Please check and try again" context = {"coin": ctp_val} return render(request, 'coinwall.html', context) Also, I want to know if I can trace the details of total user changed in a particular coinid. … -
Add to serializer data before returning
I have an endpoint which looks like this @api_view(['GET']) def products_view(request): some_data = 123 products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) I want to add the some_data variable to the JSON this endpoint returns. How could I do that?