Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django swap not null fields - getting IntegrityError due to unique_together
My model holds a not null ForeignKey to another model, which is also part of the unique_together. class MyModel: ... a_link = models.ForeignKey(AnotherModel, null=False) ... class Meta: unique_together = ((a_link, )) Now I want to swap a_link between instances of MyModel a and b. (In reality a few more than two). I get an IntegrityError with Duplicate entry, which is perhaps not so strange but even atomic() doesn't change anything to the better: with atomic(): for obj, to_ in a_list.items(): obj.type = to_ obj.save() Even setting them outside and just looping the save()within the atomic() doesn't help. Am I stuck with creating an algo that puts the objects in the correct order, use a tmp variable for one of them, loop the list and then set the last one? -
Existing username form validation, django
When a user enters the same username as an existing user I get the error: "The view account.views.register didn't return an HttpResponse object. It returned None instead." I attempted to add a validation check that searches for existing users however I can't seem to get it to work. it's my first time using Django, any advise would be appreciated! views.py def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('') else: form = RegistrationForm() args = {'form': form} return render(request, 'account/registration.html', args) forms.py class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) username = forms.CharField(max_length=50, required=True) class Meta: model = User fields = ( 'username', 'email', 'password1', 'password2' ) def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.username = self.cleaned_data['username'] user.email = self.cleaned_data['email'] if commit: user.save() return user def clean_username(self): username = self.cleaned_data.get('username') queryset = User.objects.filter(username=username) if queryset.exists(): raise forms.ValidationError("Username is taken") return username traceback Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 137, in _get_response "returned None instead." % (callback.module, view_name) ValueError: The view accounts.views.register didn't return an HttpResponse object. It returned None instead. "POST /account/register/ HTTP/1.1" 500 54493 -
Serializing foreign keys as list in DRF
I want to serialize the data class Main(models.Model): title = models.CharField() class ForeignKey(models.Model): main = models.ForeignKey(Main,on_related='foreign_key') I want to get the result like {'title':'hello', 'foreign_key':'['foreign_key1','foreign_key2','foreign_key3']' I first thought I could make it work in the 'views.py', but some documents told me that there is a thing like 'listField' in serializer, which has too little examples.. What would be the way here? -
Django how to send variable to ajax call and update javascript value
I have a script on my page that takes a variable, but this variable is first created after a form is submitted. How can I create an AJAX call to my views after a user hits the submit button and then request the variable myID and then update my javascript on the html page with the value that it received? The javascript that needs to be updated: <script> stripe.redirectToCheckout({ sessionId: "{{myID}}", }).then(function (result) { // Diplay result.error.message to your customer }); </script> <script> -
CreateView asking for object pk or slug
This is the error I get when I try to visit my PostCreateView: AttributeError at /posts/new/ Generic detail view PostCreateView must be called with either an object pk or a slug in the URLconf. It worked earlier but now its not working at all. html <a class="btn btn-primary" href="{% url 'post-create' %}" aria-label="Create"> views.py class PostCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView): model = Post fields = ['article_title', 'content', 'article_image', 'game', 'platform'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user.groups.filter(name=post.game).exists(): return True return False urls.py path('posts/new/', PostCreateView.as_view(), name='post-create'), -
object is not subscriptable error when attempting to access element in dictionary
I'm trying to access elements from a shopping cart object returned via a context processor in a django view. The abridged code and relevant code is: def payment_order(request): ... cart = Cart(request) ... charge = stripe.Charge.create( amount=cart['price'], This results in an error: TypeError at /relevant/url/ 'Cart' object is not subscriptable I can access items in my cart via a for loop later on in the code without issue, like so: for item in cart: OrderItem.objects.create( product=item['product'], price=item['price'], I had thought the cart object was just a dictionary, but if that is the case why can't I access elements from it directly? How can I access the 'price' element in my cart dictionary? -
Django: How to move from auto_add_now/auto_now to editable date fields
We have a Model that includes an auto_add_now field and have decided that we need to be able to occasionally update it manually. However, in writing the DRF serializer / view it's unclear how best to handle this, since it's normally not editable we need to make a change. We're considering using the pre-save trick (AutoDateTimeField): Django auto_now and auto_now_add but that answer is 9 years old. class AutoDateTimeField(models.DateTimeField): def pre_save(self, model_instance, add): return timezone.now() #usage created_at = models.DateField(default=timezone.now) updated_at = models.AutoDateTimeField(default=timezone.now) Are there any downsides? This is in an abstract base class which affects many models. Is there a better way (Django 1.11.7)? -
Django-autocomplete-light - can't see dynamically selected option
I'm trying to dynamically select an option in on ModelSelect2 field. widget 'country':autocomplete.ModelSelect2(url='addresses:country-autocomplete'), I tried: $('select[name="country"]').val(1); but it didn't do anything: > s.val() > null The same happens when I append .trigger('change'); So I tried to append Option (it's through AJAX so it can be empty) > var newOption = new Option('Kamkoľvek', 22357, false, false); > undefined > s.append(newOption) > r.fn.init [select#id_country.form-control.select2-hidden-accessible, prevObject: r.fn.init(1)] > s.val(22357) > r.fn.init [select#id_country.form-control.select2-hidden-accessible, prevObject: r.fn.init(1)] > s.val() > "22357" > s.trigger('change') > r.fn.init [select#id_country.form-control.select2-hidden-accessible, prevObject: r.fn.init(1)] So now, the option is set but I can't see anything visually (like nothing was selected). Why it is not visible? -
Django not such column operationalError at /
I'm trying to add a new textfield to my Post model but for some reason I keep running into and error which says: no such column: home_post.road_name, Note I'm adding this field after the initial migration. I have ran python manage.py makemigrations after adding road_name to my models.py file. The only thing I did notice is instead of updating the file within the migrations folder it created a new one. But beyond that I'm hopeless. Thanks for any help! models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() road_name = models.CharField(max_length=150, default='') 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('project-detail', kwargs={'pk': self.pk}) views.py class ProjectDetailView(DetailView): model = Post class ProjectCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class ProjectUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False class ProjectDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post success_url = '/' def test_func(self): post = self.get_object() if self.request.user == post.author: … -
django-stripe error: "Your card's expiration year is invalid" when testing, no matter year entered
I'm using a django-strip with a view to create a charge, and if that is successful save some local items to a db. I'm getting an error: CardError at /relevant/url Request req_tdxeiuSSMmJi89: Your card's expiration year is invalid. Originally, I had my year set to use the entire year. I tried changing this to use just the last 2 digits, and when I came across this question, it seemed like that would fix the issue, however it has made no difference. In my stripe dashboard, I can see what is being passed to stripe, and the error seems to be caused by the card year not being passed to stripe correctly. From my stripe dashboard: Request POST body { "card": { "number": "************4242", "exp_month": "10", "exp_year": "0", "cvc": "*********" } } I am extending a form in my view to have fields used to process a payment, as I won't be saving that information to my db, and so those fields do not correspond to a model. My view: def payment_order(request): card_num = request.POST.get('card_num', False) exp_month = request.POST.get('exp_month', False) exp_year = request.POST.get('exp_year ', False) cvc = request.POST.get('cvc', False) email = request.POST.get('email', False) cart = Cart(request) if request.method == 'POST': form … -
Django submit form and redirect to payment page then do form stuff
I'm trying to integrate Stripe Checkout to have the customer pay when submitting the form. This integration redirects the customer to Stripe's page to do the payment. How can I make Django remember the input values from the Form after the payment is submitted on the redirected page? Can I create a custom URL that remembers the values? Also their script requires a payment ID which I serve through a variable but this variable is first created once the form is submitted. I can't change a javascript variable dynamically once the page is rendered, right? Javascript <script> stripe.redirectToCheckout({ sessionId: "{{context}}", }).then(function (result) { // Diplay result.error.message to your customer }); </script> Python code to create the payment which is called after form submission stripeUID = str(uuid.uuid4()) payment = stripe.checkout.Session.create( success_url="https://mypage.com/succes", cancel_url="https://mypage.com/error", payment_method_types=["card"], client_reference_id= stripeUID, line_items=[ { "amount": 2000242, "quantity": 1, "name": "Blender rendering", "currency": "usd", } ] ) context = payment.id -
Data driven drop down menu Django
I am using a database "selectCountry" and I want to select all the country names in the database to get populated in the html dropdown menu. Following is my code models.py class selectCountry(models.Model): selectCountryoption = models.CharField(max_length = 30) views.py def loadCountries(request): countries = selectCountry.objects.all() return render(request, 'register/bg-pages.html', {'countries': countries}) html code <form action="."> <select name="Country" id="searchOption"> <option value="">---------</option> {% for country in countries %} <option value="{{ countries.selectCountryoption }}">{{ countries.selectCountryoption }}</option> {% endfor %} </select> <input type="submit" value="submit" name="submit" </form> </p> -
Time not saving in UTC
I have a form with a TimeField, which takes inputs from a dynamically created dropdown. All my other forms successfully convert dates and times based on a users timezone, and save them in the database as UTC. This doesn't seem to be happening with my time input on this specific form. I believe it is because it takes a string value from a list I have, but I am not sure how to change that since the list is needed for the way my dynamically generated input list is recorded. I would appreciate any help with finding a way to still dynamically generate my time dropdown and save it in UTC. HTML <div class="form-group"> <label>Time</label> {{ form.booked_time }} </div> models.py class Booked(models.Model): booked_time = models.TimeField(null=True, blank=True) forms.py class BookedForm(forms.ModelForm): booked_time = forms.ChoiceField(choices=time_list, widget=forms.Select(attrs={'class' : 'form-control', 'id' : 'time', 'required' : 'True'})) 'booked_time') with a time_list that goes something like this ('', 'Time'), ('8:00 am', '8:00 am'), ('8:15 am', '8:15 am'), ('8:30 am', '8:30 am'), views.py def book_lesson(request, lesson_id): if request.user.is_authenticated and request.user.time_zone: activate(request.user.time_zone) else: deactivate() lesson = Lesson.objects.get(id=lesson_id) if request.method == 'POST': form = BookedForm(request.POST) if form.is_valid(): book = form.save(commit=False) book.student_user = request.user book.teacher_user = lesson.user book.save() messages.success(request,'Lesson was successfully … -
Django centos server not receiving requests
I just deployed my Django project to a local CentOS server for testing. The problem is that after I run my server like: 192.168.1.4 (server ip), and run in port:3001 and then I send a request from another computer on the same LAN this requests are not being received by the server. Local request from the server to the server are working fine. Also: ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True Django: 2.1 CentOs: 7 The command netstat shows that indeed the port is listening. The port has already been opened in the router. -
Django ModelForm input fields from Model doesn't show
So I'm just getting started with django and am trying to implement a ModelForm. However something goes wrong, the input fields from the model doesnt appeare in the HTML, but the submit-button which is implemented in the HTML does. I would appriciate it if anyone could tell me where I do wrong or can refer me to a source that would help me out. form.py from .models import Article from django import forms class Article_form(forms.ModelForm): class Meta: model = Article fields = [ 'title', 'content' ] models.py from django.db import models # Create your models here. class Article(models.Model): title = models.CharField(max_length = 120) content = models.TextField(max_length = None) views.py from django.shortcuts import render from .forms import Article_form from .models import Article # Create your views here. def create_article(request): form = Article_form(request.POST or None) if form.is_valid(): form.save() form = Article_form() context = { 'form': form } return render(request, "articles/form.html", context) form.html <form method="POST">{% csrf_token %} {{ form.as_p }} <input type="submit" value="OK"> </form> index.html <html> <body> <h2>This is a page</h2> {% include 'articles/form.html' %} </body> </html> If you need any other information please tell me! Thank you! -
Automatically create child object from parent - Django 1.11
I have a parent class: class Parent(models.Model): field1 = model.CharField() field2 = model.CharField() And a child: class Child1(Parent): pass Is there a possible way to create a child object whenever a perent is saved? The child inherits all the fields from the parent, but, regardless if filled or not, I would need to create a new child object whenever a parent is saved. Any ideas? -
Adding fields from another model into admin inlines - Django admin
COnsider this: @admin.register(MyModel) MyModelAdmin(admin.ModelAdmin): fieldsets = [ ('Field1', {'fields': ['field1']}), ('Field2', {'fields': ['field2']}), ... ] list_display = ('field1', 'field2') Let's say I have another model for my admin: @admin.register(AnotherModel) AnotherModelAdmin(admin.ModelAdmin): fieldsets = [ ('Field1', {'fields': ['field3']}), ('Field2', {'fields': ['field4']}), ... ] list_display = ('field3', 'field4') So, I need to show field3 from AnotherModelAdmin into MyModelAdmin inlines. How can I achieve this? -
Django cannot clear uploaded postcover
i have a postmodel and a postform at my django app but if i try to delete the postcover from the form i get the following error: The 'postcover' attribute has no file associated with it. i dont understand why this is happening because for the postattachment field this is working fine. models.py class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Post Title", max_length=40) content = models.TextField(verbose_name="Post Content", max_length=5000) tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=50, blank=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True) postattachment = fields.FileField( verbose_name="Post Attachment", blank=True, null=True, upload_to=get_file_path_user_uploads, validators=[file_extension_postattachment, file_size_postattachment] ) postcover = fields.ImageField( null=True, blank=True, upload_to=get_file_path_user_uploads, validators=[default_image_size, default_image_file_extension], dependencies=[FileDependency(processor=ImageProcessor( format='PNG', quality=99, scale={'max_width': 700, 'max_height': 700}))]) up_vote = models.IntegerField(verbose_name='Post Up-Vote(s)', default=0) down_vote = models.IntegerField(verbose_name='Post Down-Vote(s)', default=0) published_date = models.DateField(auto_now_add=True, null=True) forms.py class PostForm(forms.ModelForm): class Meta: model = Post widgets = { 'title': forms.TextInput(attrs={'placeholder': 'e.g.: Something about Mr. Nobody'}), 'tag': forms.TextInput(attrs={ 'placeholder': 'e.g.: April, Cars, Montana'}), } fields = ['title', 'category', 'content', 'tag', 'postcover', 'postattachment' ] captcha = CaptchaField() field_order = ['title', 'category', 'content', 'tag', 'postcover', 'postattachment', 'captcha' ] def __init__(self, *args, **kwargs): kwargs.setdefault('label_suffix', '') super(PostForm, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs.update({'class': 'blablablablaaaa'}) ... -
how to save 1 form and a create view in a single template
I need your help, I have the following problem. it is an information table In these moments already it keeps the reason of the change that is the texfield. I attach the corresponding models: class Condition(models.Model): UNITS_OF_MEASURE =( ('P', '%'), ('C', '°C'), ('F', '°F'), ('CM','cm'), ('MM', 'mm'), ('S', 'Seg'), ) name = models.CharField("Nombre:",max_length=20) nominal_value = models.DecimalField("Valor Nominal:", max_digits=5, decimal_places=2) min_value = models.DecimalField("Valor Minimo:", max_digits=5, decimal_places=2) max_value = models.DecimalField("Valor Maximo:", max_digits=5, decimal_places=2) unit_of_measure = models.CharField("Unidad de medicion",choices=UNITS_OF_MEASURE,max_length=20) last_value = models.DecimalField("Valor de Ultima corrida:", max_digits=5, decimal_places=2) is_reference = models.BooleanField() job_instruction = models.ForeignKey(JobInstruction,on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse("conditions:list_condition") class ChangeLog(models.Model): STATES =( ('ONREVIEW', 'En revision'), ('ACCEPTED', 'Aceptado'), ('DENIED', 'Denegado'), ) job_instruction= models.ForeignKey(JobInstruction,on_delete=models.CASCADE) date_created = models.DateField("Fecha creacion:",auto_now_add=True) state = models.CharField(max_length=20, choices=STATES, default="En revision") author = models.ForeignKey(User,on_delete=models.CASCADE, null = True, blank= True) reason_for_change = models.TextField("Razon de cambio") def __str__(self): return f'{self.job_instruction}' class ValueChange(models.Model): condition = models.ForeignKey(Condition,on_delete=models.CASCADE) changeLog = models.ForeignKey(ChangeLog,on_delete=models.CASCADE) value = models.DecimalField("Valor", max_digits=5, decimal_places=2) def __str__(self): return f'{self.condition}' Now in the views I have the following. class CreateChangeLog(SuccessMessageMixin,generic.CreateView): template_name= "conditions/create_change_log.html" model = ChangeLog fields= [ 'reason_for_change', ] success_url="/" success_message = " was created successfully" form_value = ValueChangeForm def get_context_data(self, **kwargs): job_queryset =JobInstruction.objects.all() job_instruction = get_object_or_404(job_queryset,pk=self.kwargs['pk']) context = super().get_context_data(**kwargs) if 'form_1' not in … -
How to validate all inlines from Django admin
I have 2 models: class Parent(models.Model): .... children = GenericRelation(Children) class Children(models.Model): .... content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) I have an admin class for the Parent model which contains inlines with Children models: class ParentAdmin(admin.ModelAdmin): inlines = [ChildrenInline] I would like to validate some fields in the inline children when the parent changes its status and the admin form is saved. Can someone help me with this problem? Thanks -
How to Change Required fields in django form for super user?
I am trying to make required form field optional for super user in my project. But i am stuck as i don't know how to do that. I want to 'is_super' boolean for required field when super user click on 'is_super' required field should become optional. Thanks Here is ScreenShot of form field: Here is my code for form.py class TrackerForm(forms.ModelForm): is_super = forms.BooleanField() class Meta: model = Tracker fields = ('is_super','cascade','Date','Technology', 'Type', 'Bandwidth_Checked_From_LSM', 'Market', 'eNB', 'LSM', 'CSMS', 'FE_Name', 'Mode_of_Communication', 'Activity', 'Activity_status', 'Site_Status_pre_Activity', 'Site_Status_post_Activity','E_Link_Status_of_BH0_for_CDU30','MJ_Object_Marked','RET','Alarms_Preventing_RET_Config','Frequency_Earfcn_Checked_from_LSM_BSM','IP_Route_or_IP_Address','Volte_MME_IP_Config','Review_LATP_Complete','Remarks','OAR_Date','OAC_Date','Lock_Unlock_Verified_By','Verify_Status','Final_Comments') ` View.py: @login_required def tracker_new(request): if request.method == "POST": form = TrackerForm(request.POST) if form.is_valid(): tracker = form.save(commit=False) tracker.admin = request.user tracker.created_date = timezone.now() tracker.save() return redirect('tracker_detail', pk=tracker.pk) else: form = TrackerForm return render(request, 'tracker/tracker_edit.html', {'form': form}) Model.py: admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,default='') cascade = models.CharField(max_length=255, default='') Technology_CHOICES1 = ( ('800', '800'), ('1900', '1900'), ) Technology = models.CharField(max_length=255, choices=Technology_CHOICES1) Type_CHOICES8 = ( ('CDU10', 'CDU10'), ('CDU20', 'CDU20'), ('CDU30', 'CDU30'), ('NA', 'NA'), ) Type = models.CharField(max_length=255, choices=Type_CHOICES8) Bandwidth_Checked_From_LSM_CHOICES10 = ( ('3', '3'), ('5', '5'), ('10', '10'), ('NA', 'NA'), ) Bandwidth_Checked_From_LSM = models.CharField(max_length=255, choices=Bandwidth_Checked_From_LSM_CHOICES10) market = ( ('Kansas', 'Kansas'), ('Alaska', 'Alaska'), ('PR / VI', 'PR / VI'), ) Market = models.CharField(max_length=255, choices=market) eNB = models.CharField(max_length=255, default='') LSM = models.CharField(max_length=255, default='') CSMS … -
Django 2.1 - 'WhereNode' object has no attribute 'output_field' error
I am trying to filter some annotations in a ViewSetlike so: queryset = Confirmation.objects.values('prediction__specimen_id').annotate( sample_id=F('target_prediction__specimen_id'), num_selected=Count('selected', filter=Q(selected=True)), num_validated=Count('validated', filter=Q(validated=True)), num_has_standard=Count('has_standard'), filter=Q(has_standard=True However, I am getting the following error: 'WhereNode' object has no attribute 'output_field' My syntax seems to be correct according to all guides. I am running Django 2.1. Any idea what's happening? Can I not do this in Django Rest Framework because of paging? -
Django- How to retain the development page
I am a newbie to Django python. Once I started populating the "urlpatterns" list in urls.py. I no longer able to see the development page. My question is how can I retain it? Thanks. -
ImportError: No module named taggit.managers
I'm trying to use the django-inline-media for my blog project such that I can put images in between sections of my blog posts. I am however running into some problems following the tutorial at https://django-inline-media.readthedocs.io/en/latest/tutorial.html The installation process is fine and following the configuration steps are ok until step 3 where it say to run the following python manage.py syncdb python manage.py collectstatic I then run into the error ImportError: No module named taggit.managers. I get this error for both commands. I don't have any luck searching on that error so I'm hoping someone will be able to help. Also, if you think there is an alternative way or a better way for me to achieve this with Django do let me know. -
I receive typerror when use request method in drf
With some help, I solved this issue. My api is work, but today I found this error when I try to access '/api/v1/docs' AttributeError at /api/v1/docs/ 'NoneType' object has no attribute 'method' I know that the error is here: def get_fields(self): fields = super().get_fields() if self.context['request'].method in ['POST', 'PATCH', 'PUT']: fields['products'] = serializers.ListField( write_only=True, child=serializers.IntegerField() ) return fields When I remove .method, the access to the /api/v1/docs/ works, but my solution to post some products in bundleproducts, doesn't work.