Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to save new email address after sending verification email
I'm creating the logic a new email address is verified with confirmation email. But I don't get how I can save the new email address after sending the verification email. I need to save the new email address somewhere so I can save it when the user checked the verification email. How does the verification logic usually work? My current code is like this views.py def change_email(request): if request.method == 'POST': form = ChangeEmailForm(request.POST) if form.is_valid(): # send the verification email here while creating a token ... to_email = form.cleaned_data.get('new_email') email = EmailMessage(subject, message, to=[to_email],) email.send() return HttpResponseRedirect... def verify_email(request, uid64, token): # user verify the new email address when checking the verification email here but how I can save the new email address the user input How I can save the new email address the user input or save the new email address value on the form so I can save it later? -
Is there a way to tell the user to re-use something from their request.POST without sending it back in the response?
I'm working in django if that is important. The user can upload data from a CSV file and it turns it into a giant formset. Currently, after they hit submit it gets sent to the backend where I do all the usual validation stuff. If anything is wrong in the formset it sends it all back with errors highlighted. It seems like a waste of bandwidth that the vast majority of what is sent back in the response is identical to what the user just sent in their request.POST. So my question is: is there a way to tell the user "Here are the errors, just add it to what you just sent me and re-render." Thanks! -
Creating update or create form view in Django
I have a model named profile and it has a one to one relationship with the User model. profile contains unnecessary information about the user like bio, gender, country, etc. So when the user signs up, they won't have a profile yet. When the user goes into settings and starts entering details, then they will have a profile. That being said, how do I create a view in Django that can both create profile details about the user or update existing information. Form class ProfileForm(ModelForm): class Meta: model = Profile fields = ['avatar', 'bio', 'gender', 'dob', 'country'] View class SettingsView(FormView): template_name = 'oauth/settings.html' form_class = ProfileForm success_url = reverse_lazy('oauth:settings') redirect_field_name = "next" -
Is there a sensible way to pickle forms in Django?
I am trying to pickle a form in Django. This is so that I can call that same point down the line from another web page. However, I'm getting an error: _pickle.PicklingError: Can't pickle <function paginator_number at 0x0000020BD0CBE840>: it's not the same object as django.contrib.admin.templatetags.admin_list.paginator_number Since pickle can't handle functions. Is there a workaround or alternative approach that's preferable? I'm wondering if it's just bad practice to pickle a form. -
How so I create a QRCode reader that reads the information and stores it in the database
I'm starting up a new project for an examination attendance that scans the qrcode of the students' identity card which contains the matriculation number and the full name information of the student. Is there a way to go about this because i am going to store the information inside the database and after the lecturer has logged in he scans twice the first time for sign-in and the second time for sign-out which would all be columns on the attendance table. Please what are your recommendations on how i should go about this project? -
settings.AUTH_USER_MODEL returns null from admin panel
I`m trying to import current user to my post model into author field But when i`m adding any post from admin panel, in author field i get '-' And i can`t figure out where problem is I`ve tried User and get_user_model and User but nothing is changed models.py: from django.db import models from django.conf import settings class Post(models.Model): title = models.CharField(max_length=50) date = models.DateField(auto_now_add=True) added_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,null=True) content = models.TextField() attachment=models.FileField(upload_to='attachment',blank='True') def __str__(self): return self.title If i remove null=True - got error NOT NULL constraint failed How can i fix it?: I can`t post img, but there is django admin panel with '-' https://i.imgur.com/hTLsMoJ.png -
What's behind of the process of making changes "on the fly" in a HTML?
What happens behind in the browser level that allows making changes on the fly on HTML files, for example using javascript to add a class to an element, or even inserting a whole structure of elements? Does it refresh the page? Is it a language level or is it the browser saving some parameters and loading then when reloading the page? I have this doubt because after adding something, it doesn't reboot the other javascript modifications I've made, while for example, using django framework, when I load the same page again, all modifications made with js are gone. -
Django-filter: Change field_name of filter for foreign key field
This is with django 2 and django-filter 2 I want to rename a filter on django-filter for a Foreignk key field, so the query parameter has a better name. But If I put the same name as the field, it is not working, and returning the hole queryset, I have the following model class ActiveJob(models.Model): amount_to_pay=models.PositiveSmallIntegerField() post_category=models.ForeignKey(post_area) title = models.CharField(max_length=128) And I want to filter by the name field of post_category, with icontains. If I define the filter with the same name as the field in ActiveJob model, it is now working (it returns me the hole queryset !! ) With the two commented lines (in the filter definition down here) I want call like this, but it is not working, it returns the hole queryset: /?post_category=Telecommunications And with the filter defined only as category, I am calling like this, and it is working ok: /?category=Telecommunications This is the filter definition class ActiveJobFilter(filters.FilterSet): min_payment = filters.NumberFilter(field_name="amount_to_pay", lookup_expr="gte") max_payment = filters.NumberFilter(field_name="amount_to_pay", lookup_expr="lte") title = filters.CharFilter(lookup_expr='icontains') #post_category = filters.CharFilter(lookup_expr='icontains', field_name='post_category__name') category = filters.CharFilter(lookup_expr='icontains', field_name='post_category__name') class Meta: model = ActiveJob fields = [ "title", "category", # "post_category", "max_payment", ] -
How do I remove this error message in ModelForm?
I'm trying to create a way to update an item of the database that has the fields CharField and ForeignKey. I want to pass the original values so that they don't have to be manually entered for each field every time, but this gives me a "Select a valid choice. That choice is not one of the available choices." warning for the group field. How do I remove this warning message? Setting the error message (in ModelForm) to something else manually still displays an empty (unordered) list item. Setting the form in UpdateUserView to form = UserForm() gets rid of the errors, but doesn't pass default values to the form. models.py class User(models.Model): username = models.CharField(max_length=50) group = models.ForeignKey(Group, on_delete=models.CASCADE) class Group(models.Model): name = models.CharField(max_length=20) description = models.CharField(max_length=200) forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ['username', 'group'] views.py class UpdateUserView(TemplateView): template_name = 'update_user.html' def get(self, request): user_id = int(request.GET.get('user_id')) user = User.objects.get(id=user_id) default_name = getattr(user, 'username') default_group = getattr(user, 'group') form = UserForm({'username': default_name, 'group': default_group}) return render(request, self.template_name, {'form': form, 'user': user}) End Result -
How to have a Django relational database with four tables?
I am creating a website using Django and have a problem with the database! I have four tables (topics, questions, answers and images). Each one of these tables has an id column and I would like to connect these four tables together. I have tried to use a ForeignKey() but that didn't work out. I am receiving an error message. I don't know if I can use ManyToManyField() in this case, because it is only one column that I am trying to connect. This is the code: from django.db import models # Create your models here. class topics(models.Model): topic_id = models.AutoField(primary_key=True) topic_level = models.BooleanField() topic_name = models.TextField() class questions(models.Model): question_id = models.AutoField(primary_key=True) description = models.TextField() questions_type = models.BooleanField() class answers(models.Model): answer_id = models.AutoField(primary_key=True) description = models.TextField() class images (models.Model): image_id = models.AutoField(primary_key=True) image_blob = models.BinaryField() This is the code with the ForeignKey(): from django.db import models # Create your models here. class topics(models.Model): topic_id = models.AutoField(primary_key=True) topic_level = models.BooleanField() topic_name = models.TextField() topic_question = models.ForeignKey(questions, on_delete=CASCADE) topic_answer = models.ForeignKey(answers, on_delete=CASCADE) topic_image = models.ForeignKey(images, on_delete=CASCADE) class questions(models.Model): question_id = models.AutoField(primary_key=True) description = models.TextField() questions_type = models.BooleanField() question_topic = models.ForeignKey(topics, on_delete=CASCADE) question_answer = models.ForeignKey(answers, on_delete=CASCADE) question_image = models.ForeignKey(images, on_delete=CASCADE) class answers(models.Model): answer_id … -
django FormWizard (formtools) how to dynamically change form_list based on request?
Would appreciate any guidance on this. Have SessionWizardView from django-formtools and I want to be able to send in different forms based on which request.user.restaurant the user belongs to / request.site is being accessed. Different restaurants are going to have different sets of forms for the signup flow and I can't figure out how to accommodate this. It seems like I need to either pass in a list of firms in urls.py .as_view() or have the forms listed ahead of time in the class. MY_TEMPLATES = { '0': '/templates/wizard_1.html', '1': '/templates/wizard_2.html', '2': '/templates/wizard_3.html' } class MySignupWizard(SessionWizardView): form_list = [AddressForm, MenuForm, HoursForm,ContactForm] def get_template_names(self): return [MY_TEMPLATES[self.steps.current]] def done(self, form_list, **kwargs): etc. Since get_template_names(self) has access to self.request, and self.request.site, I think I could have MY_TEMPLATES be a nested dictionary, and pass in self.request.site along with the current step to these. Although is there a way to pass in data directly to these templates? Like do a query and pass in Restaurant data to each template? But I can't figure out how to dynamically modify form_list. There are the standard four forms above, but some restaurants only want three forms or slightly different forms. I'd like to do something like : restaurant … -
How can i redirect my homepage to my main domain using Django
I am trying to redirect my homepage url path https://www.va-glazing.com/home/ url to my main domain, which is https://www.va-glazing.com. I am hosting my site on python anywhere and got the domain from godaddy.com. thanks in advance! -
How could I get the latest blog posts for Mezzanine page?
I'm new on Mezzanine and I want to display the 8 latest post on a custom section of the home page. I already built the QuerySet: BlogPost.objects.filter(publish_date__isnull=False).order_by('-publish_date')[:8] I've already checked templates/blog/blog_post_list.html but I'm not clear on how can I pass the QuerySet result to the view. -
Django handling image using formset error
I am new to django formset, and now i wanted to get the image from an input file field . whenever i try to print the value of the cleaned_data i get none. # Create the formset, specifying the form and formset we want to use. PictureFormSet = formset_factory(PictureForm) profile_form = ProfileForm(request.POST, user=user) picture_formset = PictureFormSet(request.POST, request.FILES) if user.username == username: if request.method == 'POST': if profile_form.is_valid() and picture_formset.is_valid(): # save user info user.first_name = profile_form.cleaned_data.get('first_name') user.last_name = profile_form.cleaned_data.get('last_name') user.save() # now save data for picture_form for picture_f in picture_formset: picture = picture_f.cleaned_data.get('form-0-pic') proffession = picture_f.cleaned_data.get('form-0-proffession') print('=======================') print(picture) print(proffession) -
How and where should I create this transactional method?
I'm using Python 3.7. In a service class, I have these statements ... article.first_appeared_date = datetime.now(timezone.utc) article.save() ArticleStat.objects.save_main_article(article) The first pair of statements updates an attribute for a single object and the second statement creates a bunch of separate objects, using the first object. What i would like is for the whole thing to be executed as a transaction, whereby everything succeeds or no changes to the database occur if something fails. I'm unclear as to best practices in Python. Where would a method like this go? Does putting it in a manager class make it transactional? -
How to make django model choice field human readable
So I have django model choice field with months class EntrySummary(models.Model): JANUARY = '1' FEBRUARY = '2' MARCH = '3' APRIL = '4' MAY = '5' JUNE = '6' JULY = '7' AUGUST = '8' SEPTEMBER = '9' OCTOBER = '10' NOVEMBER = '11' DECEMBER = '12' MONTH_CHOICES = ( (JANUARY, 'January'), (FEBRUARY, 'February'), (MARCH, 'March'), (APRIL, 'April'), (MAY, 'May'), (JUNE, 'June'), (JULY, 'July'), (AUGUST, 'August'), (SEPTEMBER, 'September'), (OCTOBER, 'October'), (NOVEMBER, 'November'), (DECEMBER, 'December'), ) name = models.CharField( max_length=255 ) month = models.CharField( max_length=2, choices = MONTH_CHOICES, default=JANUARY, ) Views.py I render it def based_onmonth(request, *args, **kwargs): monthId = request.GET.get('month') monthEntry = EntrySummary.objects.filter(month=monthId) return render(request, 'app/js_templates/month_dropdown_list.html', {'MonthItem': monthId}) html template: <option value="">---------</option> {% for item in MonthItem %} <p>item.name</p> <option value="{{ item }}">{{ item }}</option> {% endfor %} Doing this i receive {'month': '2'} in my select section My question is how to print just 2 without month -
I am getting an "unable to import" error in django
I am Elvis, I am new to django and I am using Visual Studio Code. but everywhere that there is :"From django." I am getting the "[pyLint] unable to import 'django....' please help -
What could be the reason why css does not work in Chrome but works in Opera?
When I tried to add styles to the Django project, they do not work in Chrome, but work in Opera. CSS are very simple, for example, margin-top should be supported by any Chrome: https://www.w3schools.com/cssref/pr_margin-top.asp But Chrome does not see it, unlike the Opera. Tell me, please, what could be the problem? I took this project as a basis: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Home_page In locallibrary\catalog\static\css\styles.css I have following code: .sidebar-nav { margin-top: 20px; background-color: skyblue; padding: 0; list-style: none; } In locallibrary\catalog\templates\base_generic.html: {% load static %} link rel="stylesheet" href="{% static 'css/styles.css' %}"> "link rel..." start with "<" but it does not copy here. In locallibrary\locallibrary\settings.py: STATIC_URL = '/static/' -
AttributeError: 'Manager' object has no attribute
I'm using Python 3.7. I'm having a lot of trouble figuring out how and where I should put a method taht creates and saves multiple objets. I have this in my models.py file class ArticleStatManager(models.Manager): def save_main_article(self, article): Then in another part of the code, I call ArticleStat.objects.save_main_article(article) but this results in the error ArticleStat.objects.save_main_article(article) AttributeError: 'Manager' object has no attribute 'save_main_article' What am I doing wrong or where should I be placing this code so taht I can invoke it properly? -
Django - Custom Form does not prepopulate initial data
I have a parent model (Venue) and a child model (Amenity). A venue can have many amenities. while configuring my initial data and presenting it with {{form.as_p}} everything works as expected. But when I try to render my own custom form, so that I can apply a loop, It doesn't pre-populate them. Here is my template: <form method="POST" class="ui form"> {% csrf_token %} {% for category in categories %} <h4 class="ui horizontal divider header"> <i class="list icon"></i> {{category.category}} </h4> <p class="ui center aligned text"><u>{{category.description}}</u></p> {% for amenity in category.amenity_set.all %} <div class="inline field"> <label for="choices_{{amenity.id}}"></label> <div class="ui checkbox"> <input id="choices_{{amenity.id}}" type="checkbox" value="{{amenity.id}}" name="choices"> <label><span data-tooltip="{{amenity.description}}" data-position="top left">{{amenity}}</span></label> </div> </div> {% endfor %} {% endfor %} <button type="submit" name="submit" class="ui button primary">Next</button> </form> my ModelForm: class AmenitiesForm(ModelForm): class Meta: model = Venue fields = ('choices',) choices = forms.ModelMultipleChoiceField(Amenity.objects.all(), widget=forms.CheckboxSelectMultiple,) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if kwargs.get('instance'): initial = kwargs.setdefault('initial', {}) initial['choices'] = [c.pk for c in kwargs['instance'].amenity_set.all()] forms.ModelForm.__init__(self, *args, **kwargs) def save(self, commit=True): instance = forms.ModelForm.save(self) instance.amenity_set.clear() instance.amenity_set.add(*self.cleaned_data['choices']) return instance and my views.py: class AddAmenitiesView(LoginRequiredMixin, CreateView): """ AddAmenitiesView is the view that prompts the user to select the amenities of their venue. """ model = Venue form_class = AmenitiesForm template_name … -
Django duplicate database lookups with inlineformset
I need help with solving an issue regarding duplicate database query's for each form in an inlineformset. I have a page where users can add and edit books belonging to an author. models.py from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=100) category_idcategory = models.ForeignKey(Category, models.DO_NOTHING) class Category(models.Model): name = models.CharField(max_length=100) forms.py from django import forms class BookForm(forms.ModelForm): class Meta: model = Books fields = '__all__' views.py instance = get_object_or_404(Author, id=id) form = inlineformset_factory(Author, Book, form=BookForm, can_delete=True, extra=5) formset = form(request.POST or None, instance=instance) if request.method == "POST": if formset.is_valid(): instanceForm = formset.save(commit=False) for obj in instanceForm: obj.save() for obj in formset.deleted_objects: obj.delete() return HttpResponseRedirect(URL) When I run the template, it performs a database query foreignkey relation to the Category model for each form in formset. How do I prevent those duplicates? I dont know where to put select_related or prefetch_related. If instances in Book model grows to a large number, the page load times are getting very slow. -
Async call and not wait while using pubnub with djagno
This is a module from PubNub that I'm using to publish a message to a topic from an API. By design I've kept the PubNub object singleton. class Pubnub: instance = None @classmethod def get(cls): if cls.instance is None: cls.instance = cls() return cls.instance def __init__(self): with open('config/config.yaml', 'r') as stream: try: conf = yaml.load(stream) pnconfig = PNConfiguration() pnconfig.subscribe_key = conf['pubnub']['publish_key'] pnconfig.publish_key = conf['pubnub']['subscribe_key'] pnconfig.ssl = False self.pubnub = PubNub(pnconfig) except yaml.YAMLError as e: pass def publish(self, channel): try: envelope = self.pubnub.publish().channel(channel).message({ 'message': True }).sync() print("publish timetoken: %d" % envelope.result.timetoken) except PubNubException as e: pass This is how I'm calling it, class SendCommunityTextMessage(views.APIView): def post(self, request, **kwargs): try: client_id = request.GET['client_id'] client_secret = request.GET['client_secret'] if Authenticator.authenticate_client(client_id, client_secret): try: //do something try: //do something more pubbub = Pubnub.get() pubbub.publish(receiver.hex_code) return Response({"Success": CommunityTextMessageSerializer(message).data}, status=status.HTTP_200_OK) except KeyError as e: return Response({"Failure": str(e)}, status=status.HTTP_400_BAD_REQUEST) except (User.DoesNotExist, CommunityRoom.DoesNotExist) as e: return Response({"Failure": str(e)}, status=status.HTTP_404_NOT_FOUND) else: return Response({"Failure": "Invalid client"}, status=status.HTTP_403_FORBIDDEN) except KeyError as _: return Response({"Failure": "Probably a typo, read the docs to use this API."}, status=status.HTTP_400_BAD_REQUEST) The issue is this slows down the API by minutes. How can I call the two lines, pubbub = Pubnub.get() pubbub.publish(receiver.hex_code) asynchronously and return out of the view … -
Django Unit Testing expected_url with random argument
I am trying to create a unit test for a view that will show a random object on a detail page. views.py def random_stuf(request): rand_stuf = Mod.objects.order_by('?').first().pk return HttpResponseRedirect(reverse('app:detail', args=(rand_stuf,))) urls.py path('detail/random/', views.random_stuf, name='random'), tests.py def test_random(self): response = self.client.get(reverse('app:random')) self.assertRedirects(response, '/detail/1/', status_code=302, target_status_code=200) the argument of the expected url will be different every time. Is there a way i can test this? -
Storing Objects in Algolia From Django
I just started with Algolia and Django and it seemed relatively easy to setup and define fine. Example of a user: from algoliasearch_django import AlgoliaIndex from algoliasearch_django.decorators import register from .models import User @register(User) class UserIndex(AlgoliaIndex): fields = ("id",'first_name', 'last_name', 'email', ''city', "state","zip_code", "phone_number") settings = {'searchableAttributes': ['first_name', 'last_name', 'email']} index_name = 'user_index' Except things started to break when I added fields that had relations to other fields: fields = ("id",'first_name', 'last_name', 'email', ''city', "state","zip_code", "phone_number", "jobs", "friends") jobs and friends both have their own models and pivot tables, and I often get errors such as Exception Value: Got AttributeError when attempting to get a value for field `id` on serializer `JobsSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'id'. What are some techniques of storing array or related values correctly in Algolia, and do it the "Django" way? -
Post comment inside Django DetailView
I need to add comments in article page. Post request receives data but not saves it. In models.py: class TemporaryComment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='temporary_comment') email = models.EmailField() message = models.TextField(max_length=1500) timestamp = models.DateTimeField(auto_now_add=True) is_approved = models.BooleanField(default=True) In forms.py: class CommentModelForm(forms.ModelForm): class Meta: model = TemporaryComment fields = [ 'article', 'email', 'message', ] in views.py: class ArticleDetailView(FormMixin, DetailView): model = Article template_name = 'article.html' form_class = CommentModelForm def get_success_url(self): return reverse_lazy('main:article', kwargs={'pk': self.object.pk}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['last_articles'] = Article.objects.filter(is_active=True).order_by('-timestamp')[:10] context['comments'] = self.object.temporary_comment.filter(is_approved=True) context['form'] = self.get_form() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super().form_valid(form) If i comment out article field in forms.py, i got this error: null value in column "article_id" violates not-null constraint. DETAIL: Failing row contains (18, username@email.com, check message, 2019-01-20 18:35:36.615955+00, t, null).. Help will be gladly accepted. Thanks for your time.