Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
models not being saved with obj.save() in django
I have this model as an extension of the built in User model: class userprofile(models.Model): phone = models.CharField(max_length=20) address = models.CharField(max_length=500) user = models.OneToOneField(User, on_delete=models.CASCADE) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: userprofile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.userprofile.save() The django form class for creation of these models are: class UserRegister(forms.Form): first_name = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'First Name'})) last_name = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'Last Name'})) username = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'Username'})) email = forms.EmailField( required=True, widget=forms.widgets.EmailInput(attrs={'placeholder': 'Email'})) password =forms.CharField(required=True, widget=forms.widgets.PasswordInput()) confirm_password =forms.CharField(required=True, widget=forms.widgets.PasswordInput()) class Meta: model=User fields=['first_name','last_name','username','email','password'] def clean(self): cleaned_data = super(UserRegister, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError( "password and confirm_password does not match" ) class UserProfileCreate(forms.Form): mobile = forms.CharField(required=True, widget=forms.widgets.NumberInput(attrs={'placeholder': 'Mobile No.'})) address = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'Delivery address'})) class Meta: model= userprofile fields=['mobile', 'address'] The HTML is like: <form class="form-horizontal" method="POST" action="{% url 'createuser' %}"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form.visible_fields %} <div class="form-group"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {{ field|add_class:'form-control' }} {% for error in field.errors %} <span class="help-block">{{ error }}</span> {% endfor %} </div> {% endfor %} {% for field in formplus.visible_fields %} <div class="form-group"> … -
How to slice a list in Django template?
I'm doing some pagination in Django.Now I want to show the pages' number which are ahead the current page,using the following code: {% for page in blogs_page.paginator.page_range|slice:"0:{{ blogs_page.number }}" %} but this seems useless,the result does the same as the following: {% for page in blogs_page.paginator.page_range %} the "slice" does not work here.So how to solve that?thanks~ -
Django/Visual Studio Tutorial - objects method error
I'm working through the Django Tutorial (here). I'm using visual studio on a Mac and VS keeps showing an error on this code: latest_question_list = Question.objects.order_by('-pub_date')[:5] The error reads Class 'Question' has no 'objects' member. The example builds a Questions Class which in fact doesn't directly have an objects member, but the code runs fine and I think that there is a built in member within Django that has objects. So that leads me to believe that the visual studio debugger is raising an error that doesn't actually exist. Is there a way to fix this? I've looked through preferences/setting and under extensions to see if there is a plugin or setting reference that could be made to Django to clear the error within Visual Studio - I didn't see anything. -
Got AttributeError when attempting to get a value for field xx
I am getting the following error in Django 2.0.4: Got AttributeError when attempting to get a value for field `answers` on serializer `QuestionSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'answer_set'. I am not sure why I might be getting this error from this code. I am trying to see how overriding get_object works class QuestionDetailComplexFilter(RetrieveAPIView): model = Question serializer_class = QuestionSerializer def get_object(self): vote = self.kwargs['vote'] id = self.kwargs['pk'] queryset = Question.objects.filter(id=id) return queryset This is what my relevant models looks like class Question(models.Model): user_id = models.CharField(max_length=36) text = models.CharField(max_length=140) created_at = models.DateTimeField(auto_now_add=True) class Answer(models.Model): question = models.ForeignKey(Question,on_delete=models.PROTECT) text = models.CharField(max_length=25) votes = models.IntegerField(default=0) This is what my serializers look like class EmbeddedAnswerSerializer(serializers.ModelSerializer): votes = serializers.IntegerField(read_only=True) class Meta: model = Answer fields = ('id', 'text', 'votes',) class QuestionSerializer(serializers.ModelSerializer): answers = EmbeddedAnswerSerializer(many=True, source='answer_set') class Meta: model = Question fields = ('id', 'answers', 'created_at', 'text', 'user_id',) Any suggestions on why my class view QuestionDetailComplexFilter is failing and giving this error ? -
Obtain values in get_object from a named regex group
This is my url url(r'^api/quest/(?P<pk>[0-9]+)/(?P<vote>[0-9]+)/$', views.QuestionDetailComplexFilter.as_view()), This is my landing spot class QuestionDetailComplexFilter(RetrieveAPIView): model = Question queryset = Question.objects.all() serializer_class = QuestionSerializer def get_object(self): vote = self.request.query_params.get('vote', None) #Not working pk = self.request.query_params.get('pk', None) #Not working So if I have something like http://127.0.0.1:8000/api/quest/1/2/ I expect pk to be 1 and vote to be 2. However I cannot extract those values any suggestions on what i might be doing wrong ? -
django how to hide specific form filed and loop data input
I am Django newbie and learner, just follow the tutorial and got stuck when I saw form field not use <input> tag. here my code model.py .... class Employee(models.Model): companyid = models.CharField(max_length=100) name = models.CharField(max_length=100) def __str__(self): return self.name def get_absolute_url(self): return reverse("system:detail",kwargs={'pk':self.pk}) .... here my system/templates/system/emp_form.html .... <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-primary" value="Submit"> </form> .... and here my view.py class EmployeeCreateView(CreateView): fields = ('nik','name') model = models.Employee def form_valid(self, form): self.object = form.save(commit=False) empcount = models.TempEmp.objects.filter(status=0).count() self.object.companyid = CID + str(datetime.date().now()) + str(empcount+1) self.object.save() return super(ModelFormMixin, self).form_valid(form) problem 1. emp_form.html use {{ form.as_p }} that show all the form, I want to hide specific field like in my case is companyid that I need to computer generated. problem 2. can i use + for str on CID + str(datetime.date().now()) + str(empcount+1) any have solution maybe?... Thank you! -
How to test input to a Django MultiValueField?
I'm currently working in a Django project which defines a custom DateTimeField as follows (in dashboard/forms/fields): import pytz from datetime import date, datetime from django import forms from django.core.exceptions import ValidationError from dashboard.forms.widgets import DateTimeWidget class DateTimeField(forms.MultiValueField): widget = DateTimeWidget DATE_FORMAT = '%B %d, %Y' TIME_FORMAT = '%I:%M %p' DATETIME_FORMAT = f'{DATE_FORMAT} {TIME_FORMAT}' def __init__(self, timezone_choices=None, timezone=None, **kwargs): fields = (forms.CharField(), forms.CharField(), forms.CharField()) super().__init__(fields=fields, **kwargs) self.timezone_choices = timezone_choices self.timezone = timezone @property def timezone_choices(self): return self._timezone_choices @timezone_choices.setter def timezone_choices(self, value): self._timezone_choices = self.widget.timezone_choices = value @property def timezone(self): return self._timezone @timezone.setter def timezone(self, value): self._timezone = self.widget.timezone = value def compress(self, data_list): try: date, time, zone = data_list tz = pytz.timezone(zone) dt = datetime.strptime(f'{date} {time}', self.DATETIME_FORMAT) return tz.localize(dt) except ValueError: return None This field is used in a form called SessionForm like so: class SessionForm(forms.ModelForm): class Meta: model = Session fields = [ 'scheduled_for', ] scheduled_for = DateTimeField( required=False, timezone_choices=Family.TIMEZONE_CHOICES ) This form includes the following clean() method, which I'd like to test: def clean(self): cleaned_data = super().clean() status = cleaned_data.get('status') location = cleaned_data.get('location') if status in [Session.SCHEDULED, Session.SCHEDULED_CALENDARED] and not cleaned_data.get('scheduled_for'): self.add_error( 'scheduled_for', f"This field is required if the status is '{Session.SCHEDULED}' or '{Session.SCHEDULED_CALENDARED}'.") return cleaned_data To this end, … -
Django Custom User and AuthenticationForm
I have found others' solutions helpful, but I still am having an issue. Using a Custom User Model and also utilizing AuthenticationForm which said it support Custom User Models, I continuously receive this error: Please enter a correct username and password. Note that both fields may be case-sensitive. My settings.py where inventory is my app name. AUTH_USER_MODEL = 'inventory.User' Here are my login portion in views.py def login_view(request): context = {} if request.method == 'POST': # print(request.POST) form = AuthenticationForm(data=request.POST) print(form) if form.is_valid(): print('yay') elif request.method == 'GET': context['form'] = AuthenticationForm() return render(request, 'inventory/login.html', context) Here is my models.py class UserManager(AbstractUserManager): def create_user(self, username, first_name, last_name, perm, password): if not username: raise ValueError('Users must have a username') if not first_name: raise ValueError('Users must have a first name') if not last_name: raise ValueError('Users must have a last name') if not perm: raise ValueError('Users must have a position') user = self.model( username=username, first_name=first_name, last_name=last_name, ) if perm == 'e': user.employee = True elif perm == 'm': user.manager = True elif perm == 'o': user.owner = True user.set_password(password) user.save(using=self._db) return user class User(AbstractBaseUser): username = models.CharField(verbose_name='username', max_length=50, unique=True,) first_name = models.CharField(verbose_name='first name', max_length=50,) last_name = models.CharField(verbose_name='last name', max_length=50,) active = models.BooleanField(default=False) employee = … -
Djano - what's a good way to create a multiselect US state field
I'm looking to create a multi-select US state field. One way to do it is to create a class and it a many to many field with another class (as listed below). Is there a way that I can include the 2 digit short code in my code below? Is there a default state list? What about zip codes our state counties? class States(models.Model): ALABAMA= 1 ALABAMA= 2 ARIZONA= 3 GEO_CHOICES = ( (ALABAMA, 'alabama'), (ALABAMA, 'alaska'), (ARIZONA, 'arizona'), ) id = models.PositiveSmallIntegerField(choices=GEO_CHOICES, primary_key=True) def __str__(self): return self.get_id_display() class Profile(models.Model): user ... state = models.ManyToManyField(States) -
Get checkbox data and save it to database django
I am creating a website where users can follow stocks and see articles based on what they follow. I am struggling to get the view that allows users to select which stocks they want to follow to work. models.py from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save class Stock(models.Model): name = models.CharField(max_length = 50) ticker = models.CharField(max_length = 50) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followed_stocks = models.ManyToManyField(Stock, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class Article(models.Model): stock = models.ForeignKey(Stock, on_delete=models.CASCADE, default = 0 ) title = models.CharField(max_length = 200) url = models.URLField() description = models.TextField() def __str__(self): return self.title forms.py: class StockFollowForm(forms.Form): stocks = forms.ModelMultipleChoiceField(required =False, widget=forms.CheckboxSelectMultiple, queryset=Stock.objects.all()) template: {% block body %} <div class = "container"> <h2 class = "text-center">Register</h2> <form method = 'post'> {% csrf_token %} {{ form }} <div class = "text-center"> <br/> <button class="btn btn-primary" type = 'submit'>Follow</button> </div> </form> </div> {% endblock %} views.py: def follow_coins(request): if request.method == "POST": form = StockFollowForm(request.POST) if form.is_valid(): request.user.profile.followed_stocks = form.cleaned_data.get('stocks_selected') request.user.save() return redirect('index') else: form = StockFollowForm() return render(request, 'core/test.html',{'form': form}) This succesfully displays a … -
Conect to Django test database
everyone. Is any way to connect to django test database using connections try: cursor = connections['test_name_of_main_db'].cursor() and also specify test db name in settings result the same: Traceback (most recent call last): File "/home/tets/4d/lib/python3.5/site-packages/django/db/utils.py", line 176, in ensure_defaults conn = self.databases[alias] KeyError: 'auto_tests' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/tets/healthware_server/component/medical/tests.py", line 72, in test_model_observation cursor = connections['auto_tests'].cursor() File "/home/tets/4d/lib/python3.5/site-packages/django/db/utils.py", line 208, in __getitem__ self.ensure_defaults(alias) File "/home/tets/4d/lib/python3.5/site-packages/django/db/utils.py", line 178, in ensure_defaults raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias) django.db.utils.ConnectionDoesNotExist: The connection auto_tests doesn't exist -
Django SerializerMethodField can't save a decimal
So, according to the docs, SerializerMethodField is a read-only field. Well in my case, it's interfering with my write: # old value is 2.5 data={'score': 1.7} serializer = ScoreTraitSerializer( score_trait, data=data, partial=True) if serializer.is_valid(): new_score_trait = serializer.save() Now if I inspect the new_score_trait, my score is still 2.5. The serializer looks as such: score = serializers.SerializerMethodField() def get_score(self, obj): if isinstance(obj.score, decimal.Decimal): return float(obj.score) else: return obj.score If I comment out my SerializerMethodField, I can save the new decimal value (but can't serialize it). So ... am I using my serializer correctly? Why does my write to the serializer hitting the SerializerMethodField? Thanks in advance -
How to send an integer from ajax without jquery?
I am trying to send an integer called 'petadid' from this js to the django view called 'petadlikeview'. But it looks like the data is not going there in the view.If i print 'petadid' in the view, it shows 'None'. Can anyone please tell me what is wrong? I am new to ajax and django. Here is my js: <script> $(document).ready(function(argument) { $.ajaxSetup({cache:false}); var element = document.getElementById("likes"); var petadid = $(this).attr("data-petadid"); element.addEventListener("click",function(){ var req = new XMLHttpRequest(); req.open("POST",'/petadlike/') req.onload = function(){ console.log(req.responseText); console.log(petadid); var data = JSON.parse(req.responseText); } req.setRequestHeader("X-CSRFToken", '{{ csrf_token }}'); var data = { 'petadid':petadid, } req.send(data); }); }); </script> And here is my django-view: def petadlikeview(request): print("vau") if request.method=="POST": print("vai") petadid = request.POST.get('petadid') print(petadid) petad = PetAd.objects.get(pk=petadid) like_count = petad.petadlikes_set.all().count() like, created = petadlikes.objects.get_or_create(user=request.user,petad=petad) print(created) if created is False: petadlikes.objects.get(user=request.user,petad=petad).delete() like_count -= 1 liked = False else: like.save() like_count += 1 liked = True dict = {'like_count':like_count} return JsonResponse(dict) return HttpResponse(str(like_count)+' people have liked this') else: return HttpResponse('Bad Request') -
Formatting Django ManyToManyField as selectable items
I have 2 questions. I have 2 models Toolcart and Tools I'm making a ManyToMany relation from Toolcart to Tools, I want to add one or more tools to the cart Question 1.- Is this the right approach for what I'm attempting to do ? Question 2.- I used a generic class to create the Toolcart object (CreateView) and get a box with all the content from Tools model. how would i go about making selectable items. Does what I'm trying to do makies sense? my models.py: class Tools(models.Model): nombre = models.CharField(max_length=250) descripcion = models.CharField(max_length=250) codigo_proveedor = models.CharField(max_length=250) categoria = models.ForeignKey('Categorias', on_delete=models.CASCADE) c_minima = models.IntegerField() c_actual = models.IntegerField() proveedor = models.ForeignKey('Proveedores', on_delete=models.CASCADE) active = models.BooleanField() def __str__(self): return self.nombre + ' ----- ' + str(self.categoria) + ' ----- ' + str(self.c_actual) class Toolcart(models.Model): designacion = models.CharField(max_length=250) contenido = models.OneToManyField(Tools) active = models.BooleanField() def __str__(self): return self.designacion my views.py: # VER CARRITO class CarritoCreateView(CreateView): model = Toolcart template_name = 'inventory/cars_form.html' fields = [ 'designacion', 'contenido', 'active', ] success_url = reverse_lazy('inventory:home') -
adding a static html page to Django project
I'm new to Django & web coding & I'm following Bucky tuts: ( Django Tutorial for Beginners - 28 - Creating a Base Template ) . & I thought of viewing the template page when requested ( PATH/templates/music/base.html ) but I don't know how to do it :( . - I searched to find that I could put something like this in urls to make it work : path('base', 'django.views.generic.simple.direct_to_template', {'music/templates/music': 'base.html'}), but didn't work , So waiting for your help ;) -
Test Django with Mysql 8.0 datatime incompatible
Test Django with Mysql 8.0 datatime incompatible. I'm trying to run tests with mysql 8.0, however I'm encountering some inconsistencies. Could someone help with this? thank you Mysql 8.0.11 Django 2.0.4 > AttributeError at /admin/login/ > >'datetime.datetime' object has no > attribute 'split' > >Request Method: > >POST Request > URL: http://localhost:8000/admin/login/?next=/admin/ > Django > Version: 2.0.4 > >Exception Type: AttributeError Exception Value: > 'datetime.datetime' object has no attribute 'split' > >Exception > Location: /usr/local/lib/python3.6/site-packages/mysql/connector/conversion.py > in _DATETIME_to_python, line 506 Python > > >Executable: /usr/local/bin/python Python Version: 3.6.5 -
Cache Django Template objects generated and used in Celery tasks
I'm building a Django app that involves sending bulk customized emails to large numbers of end users. I'm doing this by storing the templates in the database (in a "Mailing" model for the content of the message and "Wrapper" model for header/footers that are commonly used), passing in the context specific to the recipient, then sending the result to the end user. One of the slowest parts is the parsing of the raw templates and generation of the Template nodelist from the content in the "Mailing" and "Wrapper" models. The most logical solution is to cache the Template object (or just the nodelist) the first time it is generated, but it appears Template objects cannot be turned into JSON or pickled in a manner that lets you send it to an external cache. Django does have a template cache feature, but this works by storing the templates in the Django process itself and not storing it in any external cache. I'm worried that even if that was possible and I did that here, I may run out of local memory, since the system may be sending multiple Templates over the lifetime of the process. It needs to be stored in … -
Django refresh page
I can not figure out how to change the page without rebooting with Ajax. urls.py urlpatterns = [ path('name/', views.name, name='name'), path('', views.index, name='index'), ] views.py def name(request): return render(request, 'site/name.html') index.html <a href="/name" id="aj">page name</a> <div id="content"> {% block content %} {% endblock %} </div> I will be very grateful if you will give me a simple code. -
Django Admin CSS files are missing
I deployed my django app to pythonanywhere.com and my admin css not working http://directdirect.pythonanywhere.com/admin/login/?next=/admin/ what do I do? I use django 2.0 -
Where should the template directory be for Django Haystack?
I'm following Haystack tutorial and trying to adapt it to my project. It says You’ll need to create a new template inside your template directory called search/indexes/myapp/note_text.txt and place the following inside: But I have put this in the 3 places I can think it might mean, but I still get TemplateDoesNotExist. What am I doing wrong? -
How to use ModelMultipleChoiceField
I am trying to create a website that allows users to follow certain stocks and read articles based on what they follow. I am having trouble creating a form for them to follow stocks as a user's Profile and Stocks have a many to many relationship, I believe I am supposed to use ModelMultipleChoiceField but cannot get it to work. models.py from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save class Stock(models.Model): name = models.CharField(max_length = 50) ticker = models.CharField(max_length = 50) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followed_stocks = models.ManyToManyField(Stock, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class Article(models.Model): stock = models.ForeignKey(Stock, on_delete=models.CASCADE, default = 0 ) title = models.CharField(max_length = 200) url = models.URLField() description = models.TextField() def __str__(self): return self.title forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Stock from django.forms import ModelMultipleChoiceField class ProfileRegistrationForm(UserCreationForm): class Meta: model = User fields = ('username', 'password1', 'password2', 'email', 'first_name' ,'last_name') class StockFollowForm(): stocks = forms.ModelMultipleChoiceField(queryset=Stock.objects.all()) views.py def test(request): if request.method == "POST": form = StockFollowForm(request.POST) if form.is_valid(): request.user.profile.followed_stocks = form.cleaned_data.get('stocks_selected') request.user.save() … -
Exception Value: __init__() missing 1 required positional argument: 'request'
when i click on login or register link of my page it show init() missing 1 required positional argument: 'request' and i m confuse on which page it is showing error so i attached my all related pages please verify them same error is showing both login and registration page only.when i click on login or register link of my page it show init() missing 1 required positional argument: 'request' and i m confuse on which page it is showing error so i attached my all related pages please verify them same error is showing both login and registration page only. urls.py path(r'register/',RegisterView.as_view(),name='register'), path(r'login/',LoginView.as_view(),name='login'), views.py def guest_register_view(request): form=GuestForm(request.POST or None) context = { "form": form } next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path=next_ or next_post or None if form.is_valid(): email=form.cleaned_data.get("email") new_guest_email=GuestEmail.objects.create(email=email) request.session['guest_email_id']=new_guest_email.id if is_safe_url(redirect_path,request.get_host()): return redirect(redirect_path) else: return redirect("/register/") return redirect("/register/") class LoginView(FormView): form_class = LoginForm success_url = '/' template_name = 'accounts/login.html' def form_valid(self,form): request=self.request next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(request, username=email, password=password) if user is not None: login(request, user) user_logged_in.send(user.__class__,instance=user,request=request) try: del request.session['guest_email_id'] except: pass if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) return super(LoginView, self).form_invalid(form) … -
How to create windows shortcur on linux
How can I create a shortcut from a file with python3 running on a linux machine. The use case is: Files are stored on a NFS share and a user can choose the file he want to access (via web frontend - Django) and the app sends a response with the shortcut/symlinc to the file. I tested around with winshell and pywin32 but wasn't able to run those on linux. Using os.symlink(src,dest) isn't working on windows. Any ideas? -
nginx error with gunicorn and django
When I access to my server through it's ip address (eg. 212.121.121.121) it works, but when I access it through the alias http://xxxx.com/ , it gives me a 404 error Any solutions? -
Django - Show message in template if this user has not accessed this page
I was wondering how might I show a new user a message such as 'First time here?' in a Django template using conditionals? e.g. {% if this_page_url_is_cached %} <h3>First time here?</h3> <h5>Follow these steps...</h5> {% endif %} What would be the best way to do this? Thanks