Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - printing variables in templates
I created an app called "jobs", basically I'd like to create new "jobs" from the admin console and be able to post it on the jobs.html page. I created the model and views but I think there is something wrong with the views that doesn't allow me to print the "jobs" on the html template. Can you please me if the error is in views.py? jobs/models.py from django.db import models # Create your models here. class post_job(models.Model): posizione= models.TextField(max_length=20) descrizione= models.TextField(max_length=20) requisiti= models.TextField(max_length=20) def __str__(self): """String for representing the MyModelName object (in Admin site etc.).""" return self.posizione jobs/admin.py from django.contrib import admin from .models import post_job # Register your models here. admin.site.register(post_job) jobs/views.py from django.shortcuts import render from .models import post_job # Create your views here. def viz_job(request): posizione = post_job.posizione print(posizione) return render(request,'jobs/jobs.html',{'posizione':posizione}) -
JSON value doesn't change inside ajax success callback function
I'm working on a django reddit clone project, just to improve my skills. I wanted to implement AJAX to it so the page doesn't refresh when someone upvotes. I made an API with django rest framework, which has upvoted and downvoted boolean values. However, when I try to change the upvoted value to false in my javascript, it doesn't work, but changing it to true when it's false works and updates the template. This is probably confusing so here is some code. class UpvoteAPIToggle(APIView): def get(self, request, id=None, format=None): post = Post.objects.get(id=id) all_post_upvotes = post.upvotes.all() all_post_downvotes = post.downvotes.all() profile = Profile.objects.get(user=self.request.user) upvoted = False downvoted = False if profile not in all_post_upvotes: post.upvotes.add(profile) downvoted = False if profile in all_post_downvotes: post.upvotes.remove(profile) upvoted = False downvoted = True else: post.downvotes.remove(profile) upvoted = True serializer = PostSerializer(all_post_upvotes, many=True, read_only=True) serialized_upvotes = serializers.serialize("json", all_post_upvotes) upvote_counter = 0 data = { "upvoted":upvoted, "downvoted": downvoted, "all_post_upvotes":serialized_upvotes, "upvote_counter":upvote_counter } return Response(data) this is the class based rest view. $.ajax({ url: upvoteUrl, data: {}, dataType: "json", success: (data)=>{ checkVote(data) } }) function checkVote(data){ if (data.upvoted){ data.upvote_counter--; data.upvoted = false }else{ data.upvote_counter++; data.upvoted = true $(".upvote-btn").css("color","orange"); $("#upvoteCounter").text(data.upvote_counter) } } Here is the jquery part from the template. It … -
Dealing with byte literals in Django unit tests
I have this line in my unit test: self.assertEqual(get_response.content, f'APIUserMiddleware User, {remote_user}, does not exists.') This fails with this output: AssertionError: "b'APIUserMiddleware: User, bad.gen, does not exists.'" != 'APIUserMiddleware User, bad.gen, does not exists.' How should I deal with the byte literal being returned from an API? -
Scrapy pipelines Django update item in database SQLite
In my Scrapy project connected with Django, I scrape pages with offerts for housing markets and save in database. In pipelines file I create unique hash_id for each item and with other data save in db. Each time I want to update db for new offerts (it works) but also for closed offerts (not displayed more on page) change status in db for 'not active'. How to do that when process_item works only for specific scrapped item? My idea was to collect all hash_id from db in list, check scrapped items if their hash_id are in. If yes, delete the hash_id from list. Then update remaining items status. But it doesn't work. My pipelines file: def hashed_list(): hashed_items_db = Offert.objects.filter(still_active = True) hashed_list=[item.hash_id for item in hashed_items_db] return hashed_list class ScraperPipeline(object): hashed_list = hashed_list() def create_hash(self, *args): ... return data def process_item(self, item, spider): ..... hash_id = self.create_hash(args) item['hash_id'] = hash_id if hash_id not in hashed_list: item.save() else: hashed_list.remove(hash_id) return item def close_spider(self, spider): for hash_item in hashed_list: obj =Offert.objects.get(hash_id=hash_item) obj.still_active = False obj.end_date = timezone.now() - timedelta(days=1) obj.save() return hashed_list How to do that? Is there any easy (??) way to update non scrapped items in db? -
Unique constraint failed - Integrity error - django
Can't find a solution for my probelm online. error message I am receiving regarding problem ----- IntegrityError at /add_user_address/ UNIQUE constraint failed: users_useraddress.user_id ------ all help greatly appreciated! views.py import re from django.urls import reverse from django.shortcuts import render, redirect, Http404, HttpResponseRedirect from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from .forms import UserRegisterForm, UserAddressForm from .models import EmailConfirmed def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your registration has been successful! Please check your email to confirm account.') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) SHA1_RE = re.compile('^[a-f0-9]{40}$') def activation_view(request, activation_key): if SHA1_RE.search(activation_key): print("activation key is real") try: instance = EmailConfirmed.objects.get(activation_key=activation_key) except EmailConfirmed.DoesNotExist: instance = None messages.success(request, f'There was an error with your request.') return HttpResponseRedirect("/") if instance is not None and not instance.confirmed: page_message = "Confirmation successful, welcome to Fuisce! " instance.confirmed = True instance.activation_key = "Confirmed" instance.save() elif instance is not None and instance.confirmed: page_message = "Already Confirmed" else: page_message = "" context = {"page_message": page_message} return render(request, "users/activation_complete.html", context) else: raise Http404 @login_required def profile(request): return render(request, 'users/profile.html') **def add_user_address(request): print(request.GET) try: redirect = request.GET.get("redirect") except: redirect = None if … -
How to submit content then display output on same page in Django
I am working with a DJango project. On my homepage I just have a drop down menu and a text area. The user will select something in the drop down menu, input some text in the text area and then push a button. Right now the only way I know how to do this is by redirecting the user to another page and displaying all the data. I was hoping I could do this by putting all the content underneath the dropdown menu, text area, and button. I am using Django. home.html <form action="{% url 'parsed' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="sel1">Select Test:</label> <select class="form-control" name="selectedtest" id="sel1"> {% for test in test %} <option value="{{ test.name }}"">{{ test.name }}</option> {% endfor %} </select> </div> <div class="form-group"> <label>Paste Event JSON</label> <textarea class="form-control" name="jsontextarea" rows="20"></textarea> <div style="text-align:center"> </br> <input class="btn btn-primary" type="submit" value="Parse"> </div> </div> </form> I will be building a large chart full of rows that I would like to display under all of this. -
Create multi model and Use them in one template in django
Well, I want to create a portfolio project using django. In the Home page of the site the main part is there's some project list and also some review list. I want to Show them both in my homepage(same template). But the problem is, I created a model for the Project list and created a Listview for that and rendered that into the homepage template. Now I don't know how to create the same for my review list. Because if I do the same, then what should I put at the urls section? So is there any option to do so? I think the question is clear, if it's not, please ask in the comment. Thanks in Advance -
How to use get_queryset inside a listview
I am struggling to use a simple get_queryset inside a listview. The goal is simply to filter the sets associated to a given cruise. My models look like this: from django.db import models class Cruise(models.Model): name = models.CharField(max_length=50) start_date = models.CharField(max_length=50) end_date = models.CharField(max_length=50) team_leader = models.CharField(max_length=50) def __str__(self): return self.name class Set(models.Model): cruise = models.ForeignKey(Cruise, on_delete=models.CASCADE) set_number = models.IntegerField() start_depth = models.IntegerField() end_depth = models.IntegerField() my urls look like this: from django.urls import path from . views import (CruiseListView, CruiseUpdateView, SetListView) from . import views urlpatterns = [ ... path('cruise/list/', CruiseListView.as_view(), name='app-cruise_list'), path('cruise/update/<pk>/', CruiseUpdateView.as_view(), name='cruise-update'), path('set/list/', SetListView.as_view(), name='set_list'), ] and the problematic view look like this: class SetListView(ListView): model = Set template_name = 'app/set_list.html' context_object_name = 'sets' #queryset = Set.objects.filter(cruise_id=1) def get_queryset(self): cruise_id = self.request.Cruise.id return Set.objects.filter(cruise_id=self.kwargs['cruise_id']) How can I filter and obtain only the sets associated with a given cruise ? I am getting a KeyError for cruise_id. Thank you, -
Ordering django model field
I have a Django model like this: COMUNI = [ ('1', 'ANA'), ('2', 'BAB'), ('3', 'ABA'), ] class ComuneConsegna(models.Model): COMUNI = COMUNI comune = models.CharField( max_length=2, choices=COMUNI, default='1', ) def __str__(self): return '{}'.format(self.get_comune_display()) Is it possible to order the model ComuneConsegna by the name reported with the method get_comune_display? Thanks -
I have two models News and Comment. I want to get the number of comments that was written to each news using templatetags
class News(models.Model): title = models.CharField(max_length=200) body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField() image = models.ImageField(upload_to='pics',blank=True,null=True) category = models.ForeignKey(Category,on_delete=models.CASCADE) class Comment(models.Model): news = models.ForeignKey(News,on_delete=models.CASCADE) message = models.TextField() user = models.ForeignKey(User,on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) -
MultiValueDictKeyError when uploading image in Django
I am getting this MultiValueDictKeyError when I try to update my profile. The exception value is profile_pic. I am using a custom user model and created the profile model separately for the profile image. enter image description here This is my views.py def profile_edit(request): if request.POST: request.user.refresh_from_db() u_form = AccountUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid and p_form.is_valid(): u_form.initial = { "email": request.POST['email'], "username": request.POST['username'], "first_name": request.POST['first_name'], "last_name": request.POST['last_name'] } p_form.initial = { "birth_date": request.POST['birth_date'], "profile_pic": request.FILES['profile_pic'] } u_form.save() p_form.save() context['success_message'] = "Profile Details Updated" else: u_form = AccountUpdateForm( initial={ "email": request.user.email, "username": request.user.username, "first_name": request.user.first_name, "last_name": request.user.last_name, } ) p_form = ProfileUpdateForm( initial={ "birth_date": request.user.profile.birth_date, "profile_pic": request.user.profile.profile_pic, } ) context = { 'u_form': u_form, 'p_form': p_form, } return render(request, "accounts/profile_edit.html", context) Models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) birth_date = models.DateField(null=True,blank=True) profile_pic = models.ImageField(upload_to='pimage/', default='pimage/default.png') def __str__(self): return f'{self.user.username} Profile' forms.py class AccountUpdateForm(forms.ModelForm): class Meta: model = Account fields = ('email', 'username', 'first_name', 'last_name') def clean_email(self): email = self.cleaned_data['email'] try: account = Account.objects.exclude(pk=self.instance.pk).get(email=email) except Account.DoesNotExist: return email raise forms.ValidationError('Email "%s" is already in use.' % account) def clean_username(self): username = self.cleaned_data['username'] try: account = Account.objects.exclude(pk=self.instance.pk).get(username=username) except Account.DoesNotExist: return username raise forms.ValidationError('Username "%s" is already in use.' % … -
django my cod dont working! Grafic picture
myAPP name catalog I have models in models.py: class Sale(models.Model): good = models.ForeignKey ("Good", help_text = 'Select good', on_delete = models.SET_NULL, null = True) quantitysales = models.IntegerField (default=1, help_text = 'Enter Qty') datesales = models.DateField (null = True, blank = True) storename = models.ForeignKey ("Store", help_text = 'Select store', on_delete = models.SET_NULL, null = True) views.py i have try to make one grafic picture for webpage def sales_filter(request): with connection.cursor() as cursor: cursor.execute(''' select datesales, alcohol, confections from catalog_Sale where datesales = %s, order by datesales; ''', ('2020-04-10',)) dt = np.array([ ( (x), float (y), float (z) ) for (x, y, z) in cursor ]) fig, ax = plt.subplots() tm = np.array(dt[:,0]) alcohol = np.array([ x for x in accumulate(dt[:,1]) ]) confections = np.array([ x for x in accumulate(dt[:,2]) ]) ax.plot(tm,alcohol) ax.plot(tm,confections) #Generate image grafic buf = io.BytesIO() fig.savefig(buf,format='PNG') return HttpResponse( buf.getvalue(), content_type='image/png') My cod have eror Exception Value: near ",": syntax error and i dont know if my cod its correct, i need help please!!! -
How to add rows to django database from python script running on Colab?
I have a python web scraping script which collects data from multiple websites by scraping. My website (built using django) shows the collected data to the users in a table. Right now what I am doing is: run the script on Google Colab everyday, download the data in csv format, delete old data from website, upload new data on it (I have a page to upload and process the csv to add data in django database). I want to do something like this: within the Python script, call a URL like: mysite.com/uploadRowFromPython?cell1=SomeData&cell2=SomeMoreData&cell3=SomeOtherData The problem is, this method will make too many requests to my site and it might crash. Is there a better way to upload data automatically? Maybe add multiple rows at once? If the script directly uploads data to the site, I can setup a cron job to make the whole process automatic, instead of me having to daily run the script, delete old records from django database, and upload new csv. -
'NoneType' object has no attribute in the form init
Gives me that error 'NoneType' object has no attribute 'tutor_courses', i am trying to get query set with courses where request.user is in the tutor field.I tried to make tutor field is null but it didn't work, how to fix that? models.py class Course(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=150, null=True, blank=True) description = models.TextField() image = models.ImageField(upload_to='courses/course_images',blank=True,null=True) cover = models.ImageField(upload_to='courses/course_covers',blank=True,null=True) tutor = models.ForeignKey(User,related_name='tutor_courses',on_delete=models.CASCADE) students = models.ForeignKey(User,related_name='course_students',blank=True,on_delete=models.CASCADE,null=True) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) category = models.ForeignKey(CourseCategories,on_delete=models.CASCADE) certificate = models.ImageField(upload_to='courses/course_certificates',blank=True,null=True) languages = LanguageField(blank=True) rank_score = models.FloatField(default=0.0) price = models.FloatField(default=0.0) discount_price = models.FloatField(blank=True, null=True) forms.py class SectionForm(forms.ModelForm): def get_tutor_courses(self): return self.user.tutor_courses course = forms.ModelChoiceField(queryset=Course.objects.all()) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(SectionForm, self).__init__(*args, **kwargs) if user is not None: tutor_courses = user.tutor_courses.all() self.fields['course'].queryset = tutor_courses if not tutor_courses: self.fields['course'].help_text = "You need to <b>create</b> a course to create sections in it" class Meta: model = CourseSections fields = ('title','course') views.py def add_section_to_course(request): section_form = SectionForm(**{'user': request.user}) if request.method == 'POST': section_form = SectionForm(request.POST,request.FILES) if section_form.is_valid(): new_section = section_form.save(commit=False) new_section.creator.add(request.user) new_section.save() return redirect(new_section.get_absolute_url()) else: section_form = SectionForm() return render(request,'courses/create_section.html',{'section_form':section_form}) -
Getting Page not found (404) error using generic views
Created models and using postgres database for CRUD operations have created models also entered path to templates in urls.py have entered all the paths and main urls.py but its giving me 404 error from crud.models import EmployeeList class EmployeeListView(ListView): model = EmployeeList class EmployeeDetailView(DetailView): model = EmployeeList class EmployeeListCreate(CreateView): model = EmployeeList fields = ['name', 'designation','salary'] success_url = reverse_lazy('employeelist_list') class EmployeeListUpdate(UpdateView): model = EmployeeList fields = ['name', 'designation','salary'] success_url = reverse_lazy('employeelist_list') class EmployeeListDelete(DeleteView): model = EmployeeList success_url = reverse_lazy('employeelist_list') urlpatterns = [ path('', views.EmployeeListView.as_view(), name='employeelist_list'), path('view/<int:pk>', views.EmployeeDetailView.as_view(), name='employeelist_view'), path('new', views.EmployeeListCreate.as_view(), name='employeelist_new'), path('view/<int:pk>', views.EmployeeDetailView.as_view(), name='employeelist_view'), path('edit/<int:pk>', views.EmployeeListUpdate.as_view(), name='employeelist_edit'), path('delete/<int:pk>', views.EmployeeListDelete.as_view(), name='employeelist_delete'), ] this is projects urls.py urlpatterns = [ path('admin/', admin.site.urls), path('crud/', include('crud.urls')), ] -
Django & Postgres: Unique Constraint not enforced?
I have a django model: class MyModel(models.Model): my_field = models.CharField(max_length=500, unique=True) ... As you can see, "my_field" must be unique. Before creating a new object I run field_value: str = 'test 12/9' try: o = MyModel.objects.get(my_field=field_value) except MyModel.DoesNotExist: o = MyModel() ... to check if an object with the unique field_value exists. So far so good. Now I realised that I do have hundrets of "duplicate" values in my_field. Here are the copied exact values from django admin: 2 StR 46/15 2 StR 46/15 As you can see, they seem to be the same. But if I copy one value to the other field in django admin and try to save it, it fails due to an object already existing with this 'my_field'. But when saving each object itself, it does not fail. I used several tools to compare the strings, I am incapable to find a diffrence. Is there a way, that django or postgres is converting these strings somewhere so they are not the same anymore? Am I missing anything? Thanks for any help! -
How to connect Admin to img src in Django
How can I connect the admin part of my django website to so that the superuser can change the images through admin instead of changing it in the code below: <div class="col-md-6"> <div class="card" style="width: 25rem;"> <img src="{% static 'images/littlewomen.jpg'%}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Little Women</h5> <p class="card-text">1949</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> -
Why my ajax request does not work in django?
I have a problem with an ajax request.I'm neophyte with jquery (and in general with javascript), so I hope that my problem is easly overcoming. Let us get straight to the crux of the matter. I have a form (created utilizing crispy_forms_tags) and after I have put a table that figure out the db created. In this table I have added also a buttom, "EDIT" that give me the possibility to modify the dataset using the a html modal tag. The script code is the following: $("form#updateUser").submit(function() { var idInput = $('input[name="formId"]').val().trim(); var codiceInput = $('input[name="formCodice"]').val().trim(); var tipologiaInput = $('input[name="formTipologia"]').val().trim(); var sottocateoriaInput = $('input[name="formSottocategoria"]').val().trim(); if (codiceInput && tipologiaInput && sottocateoriaInput) { // Create Ajax Call $.ajax({ url: '{% url "crud_ajax_update" %}', data: { 'id': idInput, 'codice': codiceInput, 'tipologia': tipologiaInput, 'sottocategoria': sottocateoriaInput }, dataType: 'json', success: function (data) { if (data.element) { updateToUserTabel(data.element); } } }); } else { alert("All fields must have a valid value."); } $('form#updateUser').trigger("reset"); $('#myModal').modal('hide'); return false; }); // Update Django Ajax Call function editUser(id) { if (id) { tr_id = "#element-" + id; codice = $(tr_id).find(".codice").text(); tipologia = $(tr_id).find(".tipologia").text(); sottocategoria = $(tr_id).find(".sottocateogira").text(); $('#form-id').val(id); $('#form-codice').val(codice); $('#form-tipologia').val(tipologia); $('#form-sottocateogira').val(sottocategoria); } } function updateToUserTabel(element){ $("#userTable #element-" + element.id).children(".userData").each(function() { var … -
Django form template without Submit button
So I am trying to save a form without using dedicated submit button in form div; <div class="col-lg-8 mt-5 cart-wrap ftco-animate"> <form method="post" id="my_form"> {% csrf_token %} <div class="cart-total mb-3"> <fieldset class="form-group"> {{ note|crispy }} </fieldset> </div> </form> </div> The button that I am using to trigger to save the form is at the bottom of page and like below: <p> <a href="{% url 'precheckout-view' %}" class="btn btn-primary py-3 px-4" type="submit" id="my_button" onclick="document.getElementById('my_form').submit()">Proceed to Checkout</a> </p> However the onclick doesn't trigger the form and the form doesn't save. Where am I doing wrong? -
how can i perform a dynamic update of a choice field of a queryset?
I've created a model with a choice field returns the level of the model:(something like..) models.py L_CHOICES = [ ('1', '1styear'), ('2', '2ndyear'), ('3', '3rdyear'), ('4', '4thyear'), ] class Student(models.Model): name = models.Charfield(primary_key = True, max_length = 255,) level = models.Charfield(max_length = 2, choices = L_CHOICES) and i want to add an action in the django administration site, so i can upgrade the level of a student, dynamically. Could anyone help me with that please. -
How to allow users to directly download a file stored in my media folder in django?
So I'm building a RESTful API for a "Development Platform" project using Django and want to setup a upload/download feature where the users of the platform can upload various files (Excel files, css files, pdf files, C# scripts, unity packages, blender files etc) and other users can then download these files through an endpoint. I have the upload file endpoint configured and properly working. At the download file endpoint, I want to receive the filename that the user wants to download and also verify the user's credentials and permissions for downloading that file and do some other model queries and checks too and finally find that file in my /media/ folder and serve it to the user's browser for auto downloading or a download pop-up on the browser. (This download file endpoint would get hit when user presses "Download File" button on the frontend). How can I achieve this in django? How do I "send" that file as a response to the user's browser for downloading? -
Iam trying to use a calendar in django to post events, in this case DJANGO-SCHEDULER(others appears to be outdated), but iam not getting sucess on it
I followed the steps in github to installed it but its not working, iam with doubts what to do in the models and views models.py class Programacao(models.Model): título = models.CharField(max_length=200) descrição = models.TextField() data_inicio = models.DateField(default=datetime.now, blank=False, null=True) data_fim = models.DateField(default=datetime.now, blank=False, null=True) imagem = models.ImageField(upload_to='imagens/%Y/%m/%d/') publicado = models.BooleanField(default=True) class Meta: verbose_name = 'Programação' verbose_name_plural = 'Programações' def __str__(self): return self.título -
Django Custom Error Page Css and JS not working
I am developing an application with Django. I prepared the error pages but; DEBUG = False ALLOWED_HOSTS = ["*"] when I do this in settings.py it does not read my css and javascript files. This is causing it and how to fix it. My urls.py and views.py content are below. urls.py urlpatterns = [ path('', index, name='home'), path('', include('admin.url')), path('data', data, name='data'), ] handler404 = 'admin.views.page_not_found' handler500 = 'admin.views.server_error' views.py def page_not_found(request, exception): return render(request, ERROR_404_TEMPLATE_NAME, status=404) def server_error(request): return render(request, ERROR_500_TEMPLATE_NAME, status=500) -
How to OR Django model field validators?
Does anyone know how to OR together Django model field validators? Something like this: example_field = models.URLField(max_length=2048, null=True, blank=True, unique=False, validators=[validator1|validator2]) I am guessing that there is a way and it involves the Q operator, but I can't find what it is exactly. -
Django 'not in' querying for related fields
I want to filter on objects that only have related objects with values in a finite set - here's how I tried to write it: trips = Trip.objects\ .filter(study=study, field_values__field__name='mode', field_values__int_value__in=modes)\ .exclude(study=study, field_values__field__name='mode', field_values__int_value__not_in=modes)\ .all() I think this would work, except 'not in' is not a valid operator. Unfortunately, 'not modes' here is an infinite set - it could be any int not in modes, so I can't 'exclude in [not modes].' How can I write this with a Django query?