Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to identify which anchor tag submitted form in django?
I have created test.html. I have two anchor tag as shown below.I want to submit form and print name of anchor tag. <div class="collapse navbar-collapse" id="navbarNavDropdown" > <ul class="navbar-nav" > <li class="nav-item" name="lang" > <a class="nav-link" id ='id' value="home" onclick="design.submit();">Home</a> </li> <li class="nav-item"> <a class="nav-link" id ='id1' value="latest_news" onclick="design.submit();">latest news </a> </li> </ul> </div> In view.py i have test func associated with test.html. def test(request): login_data = request.POST.dict() print("succeed") print(login_data) return render(request,'test.html') My aim is when one click the link it will submit form,I will identify which link is clicked and call further code according to it. But, I do not know how to do it.Please Help. -
Saving image of <image> tag in django
I want to save image of tag of html to database using Django. <form method="post" name="data" enctype="multipart/form-data"><br>{% csrf_token %} <image id="theimage" name="theimage"></image> <input class="btn btn-outline-secondary btn-md " type="submit" name="submit" id="submit" value="Upload"> </form> -
in django how to display all videos in static folder in a single page
I want to built a page which will display all the videos in static folder and able to play them (not just listing the video file name). -
Possible permission issue with upstart script/uwsgi
I'm trying to configure an Apache/uwsgi/Django app on a Centos 7. I've been able to set apache to proxy requests to uwsgi. I also set an ini file to link uwsgi with my Django app. The point is that I'm missing something with the systemd service to start the uwsgi server. I suspect is some permissions issue. if I manually run the server with uwsgi --ini /home/foo/env/app/uwsgi.ini then everything works like a charm but when I start the server with systemctl start uwsgi that corresponds to a configured service, the server starts with no errors but certain views on my app just fail. Watching logs I see many errors like these ones During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/foo/env/lib/python3.6/site-packages/django/template/base.py", line 903, in _resolve_lookup (bit, current)) # missing attribute Traceback (most recent call last): File "/home/foo/env/lib/python3.6/site-packages/django/template/base.py", line 882, in _resolve_lookup current = current[bit] File "/home/foo/env/lib/python3.6/site-packages/django/template/context.py", line 87, in __getitem__ raise KeyError(key) KeyError: 'form' During handling of the above exception, another exception occurred: File "/usr/lib64/python3.6/traceback.py", line 105, in print_exception print(line, file=file, end="") UnicodeEncodeError: 'ascii' codec can't encode character '\xf8' in position 18057: ordinal not in range(128) This same views work perfectly when starting … -
How can i copy the current row of a model to other in Django?
After I create a blog I have two submit buttons one to post an article in my profile which only I can see and other to post it in homepage as well as in my profile where all users can see but I can't figure out how to make second submit button work properly #Model MyLane in mylane/models.py class MyLane(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=25) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('my-lane') # Model Home in home/models.py class Home(models.Model): title = models.ForeignKey(MyLane, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title #Createview in mylane/views.py class MyLaneCreateView(LoginRequiredMixin, CreateView): model = MyLane fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_success_url(self): if 'homepost' in self.request.POST: mylane = MyLane.objects.get("??") home = Home(title=mylane.title, content=mylane.content, author=self.request.user) home.save() url = reverse('home') else: url = reverse('my-lane') return url -
no such table: form1_user
I have tried all previous solutions such as syncdb, migrate, makemigrations etc. I am still not getting the program to work. My models.py class Role(models.Model): ROLE_CHOICES = ( (1,'ADMIN'), (2,'HR'), (3,'MGR'), (4,'EMP'), ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES,primary_key=True) def ___str___ (self): return self.get_id_display() class User(AbstractUser): roles = models.ManyToManyField(Role) class Admins(models.Model): user = models.PositiveSmallIntegerField(choices=Role.ROLE_CHOICES) first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) class HRs(models.Model): user = models.PositiveSmallIntegerField(choices=Role.ROLE_CHOICES) first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) Then here is my views.py class AdminSignUpView(CreateView): model = User form_class = AdminSignUpForm template_name = 'form1/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'ADMIN' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('/form1/forms/') class HRSignUpView(CreateView): model = User form_class = HRSignUpForm template_name = 'form1/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'HR' return super().get_context_data(**kwargs) def form_valid(self,form): user = form.save() login(self.request, user) return redirect('/form1/forms') Here is my forms.py class AdminSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fname = forms.CharField(max_length=256) lname = forms.CharField(max_length=256) @transaction.atomic def save(self): user = super().save(commit=False) user.roles = 1 user.save() admin1 = Admins.objects.create(user=user) admin1.first_name.add(*self.cleaned_data.get('fname')) admin1.last_name.add(*self.cleaned_data.get('lname')) return user class HRSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User @transaction.atomic() def save(self, commit=True): user = super().save(commit=False) user.roles = 2 user.save() hr1 = HRs.objects.create(user=user) hr1.first_name.add(*self.cleaned_data.get('fname')) hr1.last_name.add(*self.cleaned_data.get('lname')) return user Finally, here is my error - OperationalError at /accounts/signup/hr/ no such … -
Unable to import Django Project onto additional computers
For the final project in my software class, my group has decided to use Django to build a web app. I created a Django project with a working Virtual Environment and have it sitting in GitHub for my teammates to be able to access and collaborate. So far, I have been able to run the website and create new apps with ease. That being said, when my teammates first pull from VCS into Pycharm Professional and configure the interpreter, they are met with this error: Cannot set up a python SDK at Python 3.8 (DeliverMe) (/Users/taylorschissel/PycharmProjects/DeliverMe/venv/bin/python) The SDK seems invalid. I have read through many posts but cannot seem to find anyone with a similar issue, so I am at a loss for causes/solutions. Here is the link to the repo: https://github.com/isaacfc4/DeliverMe -
Difficulty adding widget to django project
Firstly I apologize for the very basic question but I am currently learning to develop and have read a lot of documentation and searched a lot but still cannot get this working. I'm building a website using Django framework am trying to add the django-bootstrap-datepicker-plus widget. I am having a lot of difficulty figuring out exactly where the different parts of code should go. I have included snippets from my model.py and forms.py files below. The forms work as they are now, but I encounter lots of problems when I try to add the datePicker widget. class PersonalInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) GENDERS = ( ('M', 'Male'), ('F', 'Female'), ) first_name = models.CharField(max_length=200, default='') surname = models.CharField(max_length=200, default='') gender = models.CharField(max_length=1, choices=GENDERS) class PersonalInformationForm(forms.ModelForm): class Meta: model = PersonalInformation fields = ['first_name', 'surname', 'gender'] Thank you very much and I apologize for the very basic question but I have spent hours trying to figure it out and am just going around in circles. -
Does enabling HTTP/2 in Daphne preclude Daphne's server pushed events feature from working?
The HTTP/2 Support section of the Daphne GitHub page (https://github.com/django/daphne#http2-support) says: Daphne only supports "normal" requests over HTTP/2 at this time; there is not yet support for extended features like Server Push. I plan on using Daphne for its server push feature. Does the above statement imply I should not even try to enable HTTP/2 because it would prevent the server push feature from working at all? -
Apache configuration for serving Django app is not working
I have installed my Django Project on the server, and it is running locally with no problem. I can make migrations and runserver works with no error. I am following this tutorial in order to use Apache to serve the project on Ubuntu, but I am having problems. The first one is where you start Django's development server and allow remote connections (./manage.py runserver 0.0.0.0:8000). When I connect from a remote browser, I get this error: Esta página no funciona 189.172.218.174 envió una respuesta no válida. ERR_INVALID_HTTP_RESPONSE I have also made al configurations to serve the app with Apache, but when a try to connect to the server from a browser, I just get a blank page. No error or anything. This is my 000-default.conf file: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last … -
Reverse for 'hire_a_crew' not found. 'hire_a_crew' is not a valid view function or pattern name
I keep on getting a NoReverseMatch at / error when i run my project here is the app level url.py from django.urls import path from . import views from justproduceit_project import settings from django.contrib.staticfiles.urls import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns app_name = 'create' urlpatterns = [ path('equipment_categories/', views.EquipmentCategoriesListView.as_view(), name='equipment_categories'), path('rent_equipment/', views.EquipmentListView.as_view(), name='equipment_home_page'), path('equipment/<slug>/', views.EquipmentDetailView.as_view(), name='equipment_detail'), path('add_to_cart/<slug>/', views.add_to_cart, name='add_to_cart'), path('remove_from_cart/<slug>/', views.remove_from_cart, name='remove_from_cart'), path('checkout/', views.checkout, name='checkout'), path('hire_a_crew/', views.CrewListView.as_view(), name='hire_a_crew'), path('start_a_project/', views.ProjectListView.as_view(), name='start_a_project'), ] here is the settings level urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('pages.urls')), path('learn/', include('learn.urls')), path('create/', include('create.urls', namespace='create')), path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] here is the template that is throwing the error <div class="dropdown-menu col-lg-12 text-center" aria-labelledby="dropdownMenuLink"> <h6 class="dropdown-header"><b>Hire a</b></h6> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'hire_a_crew' %}">Crew</a> <a class="dropdown-item" href="#">Director</a> <a class="dropdown-item" href="#">Producer</a> <a class="dropdown-item" href="#">Writer</a> <a class="dropdown-item" href="#">Cinematographer</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'equipment_home_page' %}" role="button">Rent equipment</a> <a class="dropdown-item" href="{% url 'start_a_project' %}" role="button">Start a project</a> </div> -
Multiple arguments from DjangoTemplateLanguage to re_path()
Suppose there's an urlpattern as such : re_path('^(app){3}/$', views.apple, name='apple'), My understanding is that if I want to use a hyperlink of this in templates, I should do as such: <a href="{% url 'apple' 'app' 'app' 'app' %}">apple</a> But what if I wanted to make this pattern? re_path('^(app){100}/$', views.apple, name='apple'), Is there a better way than spamming arguments? -
In forms.ModelForm, Select dropdown not displaying values in queryset() correctly
[models.py] from django.contrib.auth.models import User class Post(models.Model): title = models.CharField() author = models.ForeignKey(User, on_delete= models.CASCADE) [forms.py] from django.contrib.auth.models import User class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title','author'] widgets = { 'author': Select(attrs={'style': 'width: 400px;'}), } def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['author'].queryset = User.objects.values_list('first_name') and this is what Select dropdown for Author shows: how do i make it shown this instead: ----- Admin John (PLEASE IGNORE: i'm just adding nonsense here otherwise stackoverflow complains "it looks like your post is mostly code. please add some more details" and won't let me submit. I don't know what else to say so i'm just adding garbage here...) -
How to use Django session variable in models.py
I wanna use the Django session variable on models.py file. How can I do it? -
django-registration invalid activation key error but user account gets activated
When I click on activation link http://127.0.0.1:8000/core/auth/activate/aoisdoaisdoaisdoiaj/ I am taken to a activation_failed page which says - The activation key you provided is invalid. But my account in the database gets activated too. If account is being activated that means activation was successful. Then why would django-registration redirect to failed page. Thanks -
Django models update calculated field according another field
I use Django and I want update many records of my model by using a calculation like in SQL like that : UPDATE table SET amount = pre_tax * 1.2 WHERE amount IS NULL; I want do that with Django ORM. I didn't find any ways to do that. This answer Django - Update model field based on another field don't use bulk update, I need a syntax that allows updating several records. -
Django Multiple form, change second forms content based on 1st form
I need to create a form where, user input from 1st form will change the form 2 content / options. For example consider in 1st form User inputs Number of building Number of floor per building Let's assume the user entered 3 building with 6,7 and 8 floors. In the next form the user has to inputs Sq Ft area per floor per building So Second form needs to have 6 rows/input for building 1, 7 rows/input entry for building 2 and 8 input entry for building 3. Thanks in advance, I am learning Django and apologize if asking a silly question. -
Error - Cannot assign QuerySet. "RfqReply.items" must be a "RequestForQuotationItem" instance. when trying to save the form
also any advise you on how to design the reply model is welcomed. or even how to better structure the views The items are created under one parent through a formset what am trying to archive unit_price, item_total_price are associated with a single item delivery_charges , overall_total, subtotal are associated with all the items models, class RfqFullPrice(models.Model): sender = models.name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="quote_sender")` receiver = models.name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="quote_reciever") requestedquotation = models.ForeignKey(RequestForQuotation, related_name="replyprice_rfq", on_delete=models.CASCADE) subtotal = MoneyField(max_digits=14, decimal_places=2, default_currency='USD', validators=[MinMoneyValidator(0)]) delivery_charges = MoneyField(max_digits=14, decimal_places=2, default_currency='USD', validators=[MinMoneyValidator(0)]) overall_total = MoneyField(max_digits=14, decimal_places=2, default_currency='USD', validators=[MinMoneyValidator(0)]) validity_start_date = models.DateField() validity_end_date = models.DateField() class ReplyItemPrice(models.Model): full_price = models.ForeignKey(RfqFullPrice, on_delete=models.CASCADE, related_name='full_price') the_rfq = models.ForeignKey(RequestForQuotation, on_delete=models.CASCADE) item = models.ForeignKey(RequestForQuotationItem, on_delete=models.CASCADE, related_name="rfq_item") quantity = models.CharField(max_length = 200, help_text='Enter the qauntity') unit_price = MoneyField(max_digits=14, decimal_places=2, default_currency='USD', validators=[MinMoneyValidator(0)]) item_total_price = MoneyField(max_digits=14, decimal_places=2, default_currency='USD', validators=[MinMoneyValidator(0)]) def quote(request, pk): template_name = 'request_quote/send_quote.html' requestedquotation = get_object_or_404(RequestForQuotation, pk=pk) items = RequestForQuotationItem.objects.filter(item=requestedquotation) if request.method == 'GET': full_priceform =QuoteFullPriceForm() item_priceform = QuoteItemPriceForm() elif request.method == 'POST': full_priceform =QuoteFullPriceForm(request.POST, request.FILES) item_priceform = QuoteItemPriceForm(request.POST, request.FILES) if full_priceform.is_valid() and item_priceform.is_valid(): full_priceform = full_priceform.save(commit=False) full_priceform.receiver = requestedquotation.sender full_priceform.sender = request.user full_priceform.requestedquotation = requestedquotation full_priceform.save() for form in item_priceform: form = item_priceform.save(commit=False) form.full_price = full_priceform form.the_rfq = requestedquotation form.item … -
Exception Value: get() returned more than one Conversation -- it returned 2
Ok, so I am getting two conversation objects returned instead of just 1. I believe I am querying correctly, but I still am getting two objects when there only should be one returned. How can I only get the one I need ? I am querying a ManyToMany field, so I may be doing something wrong with that. Error line conversation, created = Conversation.objects.filter(members = request.user).filter(members= profile_id).get_or_create() views.py/message def message (request, profile_id): if request.method == 'POST': form = MessageForm(request.POST, instance= request.user, sender=request.user, conversation = conversation, message=message, date=date) if form.is_valid(): form.save() return redirect ('dating_app:messages.html') else: conversation, created = Conversation.objects.filter(members = request.user).filter(members= profile_id).get_or_create() form = MessageForm(instance= request.user, sender=request.user, conversation= conversation, message=message, date=date) context = {'form' : form } return render(request, 'dating_app:messages.html', context) models.py class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): if not email: raise ValueError("You must creat an email") if not username: raise ValueError("You must create a username!") if not description: raise ValueError("You must write a description") if not photo: raise ValueError("You must upload a photo") user = self.model( email=self.normalize_email(email), username = username, description= description, photo= photo, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email,description,photo, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, description=description, photo=photo, ) user.is_admin=True user.is_staff=True user.is_superuser=True user.save(using=self._db) return user … -
How do I use conditional statement for different HTML output in Django?
I'd like to use different Bootstrap layouts depending on how many images are found. Currently, I can get a list of images stored in Postgres by doing this: {% for image in post.images %} <div class="d-flex"> <div class="col-md-6 mb-1"> <a href="javascript:void();"><img src="/media/{{ image }}" alt="post-image" class="img-fluid rounded w-100"></a> </div> <div class="col-md-6 row m-0 p-0"> <div class="col-sm-12"> <a href="javascript:void();"><img src="images/page-img/p1.jpg" alt="post-image" class="img-fluid rounded w-100"></a> </div> <div class="col-sm-12 mt-3"> <a href="javascript:void();"><img src="images/page-img/p1.jpg" alt="post-image" class="img-fluid rounded w-100"></a> </div> </div> </div> {% endfor %} In my database, I have images listed listed like: {"/user01/post/Annotation 2020-04-04 132805.png","/user01/post/Annotation 2020-04-05 093855.png","/user01/post/Annotation 2020-04-05 100056.png",/user01/post/default.jpg,/user01/post/Django01.png,/user01/post/Django02.png} I wanted to use an if/then/else statement that would return the amount of images and then only use a specified bootstrap class depending on the image count. post.image.count did not work and I'm wondering how I can get the count of the images. -
How IIS recognize Chinese character in URL
I was developing a django project and deploying it on IIS 7.5. I was using fileField in the model and try to upload files in the django admin. Some of the file names are in Chinese. Before I deploy it on IIS 7.5, if I run the project with python manage.py runserver on the terminal, I can download the uploaded file with Chinese name. But after I deploy it on IIS, it seems like it can not recognized Chinese character. And it gives me an error like this: error pic link Does any one knows what the problem is? I hope I explained the question with enough information. -
includes every template along with its CSS in Django
I'm trying to make every template along with its CSS like Angular or Vue Js so I have done some tries and it's work well here is my shote: <head> <style> {% include "style.css" %} {% block style-custom %}{% endblock %} </style> </head> and for every template: {% block style-custom %} /* some styles */ {% endblock style-custom %} the problem with this way I haven't the ability to change my style like in real CSS it's like a text so I'm asking if there is another way to write my own style inside style tag, like that I will have the ability to change my own styles as I want. -
Which way shall I use foreign key in Django
I have two models, Employee and Withdraw. Which way shall I do the referencing? Like this, as Employee have 0-many withdraws, class Withdraw(models.Model): amount = models.IntegerField(default=0) class Employee(models.Model): name = models.CharField(max_length=200) withdraw = models.ForeignKey(Withdraw, on_delete=models.CASCADE, null=True, blank=True) OR class Withdraw(models.Model): amount = models.IntegerField(default=0) employee = models.ForeignKey(Employee, on_delete=models.CASCADE) class Employee(models.Model): name = models.CharField(max_length=200) What are the pros/cons? Which would you use? -
How to access media files uploaded via a Django form?
I am accepting an image from the user in a form in Django. How do I access the uploaded image to show it in the web browser? This is what I have in settings.py MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' This is in my models.py class Hotel(models.Model): name = models.CharField(max_length=50) image = models.ImageField(upload_to="images/") Also, I have added the if settings.DEBUG: urlpatterns +=static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) in urls.py I tried to access the image as def image_view(request): if request.method=='POST': farm = hotelForm(); form = hotelForm(request.POST,request.FILES) if form.is_valid(): form.save() modelff = Hotel(name=request.POST['name'],image = request.FILES['image']) # print(modelff.image.url) return render(request,'djangoform.html',{"form":farm,"uploaded_data_url":modelff.image.url}) else: form = hotelForm() return render(request,'djangoform.html',{"form":form}) And in my template, I accessed the image as <img src="{{uploaded_data_url}}">. But the image does not show up and the console shows image not found. P.S. I have seen How to access media files in django How to access uploaded files in Django? https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user-during-development Django : accessing uploaded picture from ImageField But none of them seem to help me. I can't find how do I include the 'images/' in my path. My uploaded_data_url shows /media/Screenshot%202020-04-18%20at%206.39.24%20PM.png while I expect it to show /media/images/Screenshot%202020-04-18%20at%206.39.24%20PM.png Where is the problem? Also, if there can be something similar to How can I get … -
How should I do a survey which shows a brownian motion which depends on the answer?
I want to do a survey in which you write the amount you want to invest, then you see simulations (brownian motions) of different portfolios that you could choose, and then you answer which one you choose. I know how to use Python and Matplotlib, but I don't know how to use Django, which I guess that would be an option. I don't have any web development experience either. What do you thing that would be the easiest way to do it? Django with some webhost? I hope there is an easier solution. Thank you very much