Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display process list in Django template
I'm trying to implement the below example in Django and list all process inside a table but I have hard times to display the information in the template. >>> import psutil >>> for proc in psutil.process_iter(): ... try: ... pinfo = proc.as_dict(attrs=['pid', 'name', 'username']) ... except psutil.NoSuchProcess: ... pass ... else: ... print(pinfo) ... {'name': 'systemd', 'pid': 1, 'username': 'root'} {'name': 'kthreadd', 'pid': 2, 'username': 'root'} {'name': 'ksoftirqd/0', 'pid': 3, 'username': 'root'} I saw the pinfo object type is a dictionary and for each process a new dictionary is created containing the attributes (pid, name, username). How can I process all these separate dictionaries and display them as table rows ? -
Django admin page dependent selection lists at forms
I have 4 hierarchical groups for item categorization. I am trying to modify admin page so after i add first and second groups, third and fourth groups creation will be dependent on selection lists. Problem is I couldnt figure out how to update selection lists. My model is as follows; class FirstGroup(models.Model): first_group_definition = models.CharField(max_length=300, verbose_name="First Group") def __str__(self): return self.first_group_definition class SecondGroup(models.Model): first_id = models.ForeignKey(FirstGroup, on_delete=models.PROTECT) second_group_definition = models.CharField(max_length=300, verbose_name="Second Group") def __str__(self): return self.second_group_definition class ThirdGroup(models.Model): first_id = models.ForeignKey(FirstGroup, on_delete=models.PROTECT) second_id = models.ForeignKey(SecondGroup, on_delete=models.PROTECT) third_group_definition = models.CharField(max_length=300, verbose_name="Third Group") def __str__(self): return self.third_group_definition class FourthGroup(models.Model): first_id = models.ForeignKey(FirstGroup, on_delete=models.PROTECT) second_id = models.ForeignKey(SecondGroup, on_delete=models.PROTECT) third_id = models.ForeignKey(ThirdGroup, on_delete=models.PROTECT) fourth_group_definition = models.CharField(max_length=300, verbose_name="Fourth Group") def __str__(self): return self.fourth_group_definition I have tried ModelAdmin.formfield_for_foreignkey but couldnt succeed. Simply, in admin page when I click on add item on FourthGroup, 3 selection lists are on the form and after I choose first group field I want second group field will be updated. After I choose second group field related 3rd groups will be present in the 3 group list. -
django: ManyToMany model fileld check number of update or add using m2m signals
hear is code: class SlamQuestion(models.Model): slam = models.OneToOneField(AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) question = models.ManyToManyField(Question) def __str__(self): return self.slam.usercode -
Django model objects do not load in Form in testing environment
Using Django 2.1.3 Getting a strange error here; I have a form multiplechoicefield that draws its choices from the values existing in a model in the database. class ChartForm(Form): P_CHOICES = tuple((p["p"], p["p"]) for p in VAR.objects.all().values("p")) p = MultipleChoiceField(widget=CheckboxSelectMultiple, choices=P_CHOICES, initial=P_CHOICES[0][1]) I am trying to run tests for a different app in the project. It throws the following error: File "/code/pyyc/forms.py", line 31, in ChartForm p = MultipleChoiceField(widget=CheckboxSelectMultiple, choices=P_CHOICES, initial=P_CHOICES[0][1]) IndexError: tuple index out of range I assumed it was just because the model objects weren't loaded. So I added in the fixtures from the VAR app. And yet, it still throws the error. Presumably, the Form is render before the test database is compiled ... ? So I am now editing the Form so that P_CHOICES is done manually, but this is obviously not ideal for the test environment. Anyone ever come across this? Is there a smart hack for this that doesn't involve commenting out lines in the Form every time you want to test? -
NoReverseMatch at /accounts/password-reset/ for Password Reset in Django
Error- In Django after submitting email in "password-reset" page, I am getting this error. NoReverseMatch at /accounts/password-reset/ Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. My Code in urls.py file- urlpatterns = [ url(r'^password-reset/', auth_views.PasswordResetView.as_view( template_name='accounts/password_reset.html'), name='password_reset'), url(r'^password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='accounts/password_reset_done.html'), name='password_reset_done'), url(r'^password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='accounts/password_reset_confirm.html'), name='password_reset_confirm'), ] I also created separate HTML files for all pages in "accounts" directory. By the way, I am following this tutorial on youtube - click here Code Screenshot Error Screenshot -
'WSGIRequest' object has no attribute 'get', what does this mean?
I'm trying to build a simple e-mail subscription app on my django website, but I keep running into problems. The lastest is: "'WSGIRequest' object has no attribute 'get'" I've been banging my head for awhile, I have no idea what this means, any help? myproject > subscribe > forms.py: from django import forms class subscribe(forms.Form): email = forms.EmailField() name = forms.CharField(max_length=100) myproject > subscribe > views.py: from django.shortcuts import render, redirect from django.contrib import messages from .forms import subscribe as sub def subscribe(request): if request.method == 'POST': form = sub(request.POST) if form.is_valid(): form.save() name= form.cleaned_data.get('name') messages.success(request, f"Thanks for subscribing, {name}!") return redirect('home') else: form = sub(request) return render(request, "subscribe/subscribe.html", {'form':form}) myproject > subscribe > templates > subscribe > subscribe.html: {% extends "myblog/base.html" %} {% block content %} <form method='POST'> {% csrf_token %} {{ form }} <button type=submit> OK </button> </form> </div> {% endblock content %} -
Django: type object 'CategoryAttributeInlineForm' has no attribute: '_meta'
I have 2 models: Categories and CategoryAdditionalAttributes that has foreign key to Categories. Also, I'm creating an inline form set for CategoryAdditionalAttributes, but I meet this error in the testing phase: models.py class Categories(models.Model): category_breadcrumb = models.CharField(max_length=512, unique=True) class Meta: app_label = 'assortment' def __str__(self): return self.category_breadcrumb class CategoryAdditionalAttribute(models.Model): category = models.ForeignKey( Categories, on_delete=models.CASCADE, related_name='additional_attributes') attribute_key = models.CharField(max_length=500) attribute_value = models.CharField(max_length=1000) class Meta: app_label = 'assortment' def __str__(self): return "{}: {}".format(str(self.attribute_key), self.attribute_value) def __unicode__(self): return "{}: {}".format(str(self.attribute_key), self.attribute_value) admin.py class CategoryAdditionalAttributeInlineFormSet(BaseInlineFormSet): class Meta: model = CategoryAdditionalAttribute fields = ['attribute_key', 'attribute_value'] def save_new_objects(self, commit=True): saved_attributes = super( CategoryAdditionalAttributeInlineFormSet, self).save_new_objects(commit) if commit: CategoryAdditionalAttributeService() .insert_additional_attributes(saved_attributes, self.deleted_forms) return saved_attributes def save_existing_objects(self, commit=True): saved_attributes = super( CategoryAdditionalAttributeInlineFormSet, self).save_existing_objects(commit) if commit: CategoryAdditionalAttributeService() .insert_additional_attributes(saved_attributes, self.deleted_forms) return saved_attributes class CategoryAttributeInline(admin.TabularInline): model = CategoryAdditionalAttribute formset = CategoryAdditionalAttributeInlineFormSet extra = 1 class CategoriesAdmin(admin.ModelAdmin): form = CategoriesForm search_fields = ['category_breadcrumb'] inlines = [CategoryAttributeInline] test class CategoryAdditionalAttributesTest(TestCase): .... def test_insert_additional_attribute_success(self): AttributeFormSet = inlineformset_factory( Categories, CategoryAdditionalAttribute, form=CategoryAdditionalAttributeInlineFormSet) data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-category': self.test_category, 'form-0-attribute_key': 'a_room', 'form-0-attribute_value': 'Kamar Mandi' } test_attribute_formset = AttributeFormSet(data) self.assertEqual(test_attribute_formset.is_valid(), True) Results Traceback (most recent call last): File "/home/varian/.local/share/virtualenvs/f1-thanos- aRnD22rB/local/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched return func(*args, **keywargs) File "/home/varian/Desktop/dekoruma/f1- thanos/thanos/apps/assortment/tests/test_admin.py", line 134, in test_insert_additional_attribute_success test_attribute_formset … -
Pandas groupby sum doesn't keep the other columns using Django
I have a problem using this line of code: user_metadata = user_metadata.groupby(['user_id', 'gender', 'age']).sum().reset_index() I have a dataframe with almost 120 columns, I need to keep user_id, gender and age, and then sum all the values of each column and keep all the 120 columns. I used this in jupyter and it works completely fine and it keeps all 120 columns. But I need to use it in django platform. So I use the same code in django, but it just keep 5 columns and dropped all other columns. (These 5 columns contain characters in their name while the others contain numbers.) Can someone help me please with this? -
Is there a simple way to create Chained Dynamic Drop Down List in Django Admin Site?
at this moment I am creating a project to learn how to use django. In this project there are three models: Category Subcategory Product And what I'm trying to achieve is to dynamically choose the corresponding subcategory after selecting the category, and thus be able to add the product. I tried to use smart_selects without results, since it is not compatible with python 3.7 I tried to filter the list of subcategories using the selected category field as a filter, without success, I think I am not formulating the code well, so that it takes the value of the category field to filter the list of subcategories dynamically. This is my code: /////////// //models.py """Z""" from django.db import models class Category(models.Model): """Z""" category_name = models.CharField("Name", max_length=50) class Meta: ordering = ('pk',) verbose_name = "Category" verbose_name_plural = "Categories" def __str__(self): """Z""" return self.category_name class Subcategory(models.Model): """Z""" subcategory_name = models.CharField("Name", max_length=50) subcategory_parent = models.ForeignKey( Category, verbose_name="Parent", on_delete=models.CASCADE) class Meta: ordering = ('pk',) verbose_name = "Subcategory" verbose_name_plural = "Subcategories" def __str__(self): return self.subcategory_name class Product(models.Model): """Z""" category = models.ForeignKey( Category, verbose_name="Category", on_delete=models.SET_NULL, null=True) subcategory = models.ForeignKey( Subcategory, verbose_name="Subcategory", on_delete=models.SET_NULL, null=True) product_name = models.CharField("Name", max_length=50, unique=True) class Meta: ordering = ('pk',) verbose_name = "Product" … -
Django or Laravel? which is better for my Startup [on hold]
I want to launch a startup on Android,IOS and web platforms.(I use REST API for Web Services) I want to know which one is better in terms of speed, efficiency, power and etc. Django or Laravel? I know a bit about python and php. -
Not able to load static files
I tried fetching static files for my website but nothing seems to work even the other stackoverflow answers. please help on this. settings.py - STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static','static_root') STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static','static_dirs') ] File is present in : parent_folder>static>static_dirs>css>cover.css HTML <html lang="en"> {% load staticfiles %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content="Aman Turate"> <title>Aman Turate - Resume</title> <link rel="stylesheet" href="{% static 'css/cover.css' %}"> -
Make the buil-in classbased view know the application namespace in Django
So,I am trying to implement password change functionality using built-in class based views(PasswordChangeView and PasswordChangeDoneView). Now, when I enter the old password, new password and confirm password fields in the built-in template and hit enter(or submit) I get a "no reverse match" error saying "Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name." I have researched a lot and found out that its because I am using the application namespace(app_name='authenticationApp' in urls.py) thats why django is not able to find the reverse. My simple question is How do I let the built-in template know that its supposed to use namespaced URL in the reverse function ? PS: I know using my own template would resolve the issue. -
Django Filter - update results without refreshing
I'm using Django-filter to filter and sort my listview queryset. Current stats - when user submit filters, the page refreshes with the new query. My goal - get the list update without having to refresh the page + have the list update on each filter selection (rather than waiting for user to select all desired filters and submit) I believe the solution will include Ajax, however I'm not sure how to get into it with Django filter and unfortunately there's no mention whatsoever in docs. Filter.py class FestivalFilter(django_filters.FilterSet): style = django_filters.MultipleChoiceFilter(choices=Festival.style_choices,widget=forms.CheckboxSelectMultiple,) camp_style = django_filters.MultipleChoiceFilter(choices=Festival.camp_style_choices,widget=forms.CheckboxSelectMultiple,) friendly = django_filters.BooleanFilter(method='avg_above3',) ..... def avg_above3(self, queryset, name, value): return queryset.annotate(avg=Avg('Festival_Reviews__{}'.format(name))).filter(avg__gt=3) views.py from django.views.generic import (TemplateView, ListView) from festival_list import models from django.views import generic from .filter import FestivalFilter from .filter_mixin import ListFilteredMixin from el_pagination.views import AjaxListView from django.contrib.auth.mixins import (LoginRequiredMixin, PermissionRequiredMixin, UserPassesTestMixin) from braces.views import SelectRelatedMixin from django.views.decorators.http import require_GET from django.urls import (reverse, reverse_lazy) from django.shortcuts import render class HomePage(ListFilteredMixin, AjaxListView): template_name = 'index.html' page_template = 'index_page.html' model = models.Festival paginate_by = 12 context_object_name = 'festivals' filter_set = FestivalFilter AjaxListView used for pagination and not related to the filtering task. template filter menu: <form action="" method="get" id="filter-form"> <div class="row filters-row text-center"> {% for style … -
Preventing more than X instances of a model from being created
I want to create some sort of validation that prevents more than 3 instance of a certain model from being created that meet a certain set of criteria. 1) These model instances are ONLY created in /admin (i.e there is no view that creates these models, thus, I can't do the validation in a view 2) My understanding is that def clean() within forms.py only applies to font facing forms that you'd see on a webpage. As these model instances are only created in the backend, again, I don't think that I can create a form and use def clean() to perform this validation 3) I considered creating a validator in my models.py to do this validation, but I'm not sure how to get the instance of the model within a validator. My understanding is that validators can only be used to validate data at a field level. This leaves me with some confusion. I'm not sure where I can perform my validation to ensure that only 3 instances of a model with X criteria is ever created. Thanks for your help! -
There is a template error with Model instances
I am creating a blog with system of comments and tags. Now I faced to a template problem with Model instances. First I put status to all new Posts as "draft" but now I set a the status to 'published' and I got this error message. If you need more code olease tell me. I tried to watch the behavior of my code when I was adding new elemets to the my code. models.py class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset()\ .filter(status='published') class Post(models.Model): STATUS_CHOICE = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=250) slug = models.CharField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now()) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICE, default='published') class Meta: ordering = ('-publish',) def __str__(self): return self.title objects = models.Manager() published = PublishedManager() tags = TaggableManager() def get_absolute_url(self): return reverse('blog_site:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) views.py def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) # List of active comment fot this post comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': # A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object bot don't save to database yet … -
Overriden Django authentication is not returning user object
I have overridden default Authentication system of Django.But this is not returning the user object. from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission class ModelBackend(object): """ Authenticates against settings.AUTH_USER_MODEL. """ def authenticate(self, username=None, password=None, **kwargs): UserModel = get_user_model() if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: user = UserModel._default_manager.get_by_natural_key(username) print("Database pass : ",user.password,"incoming pass : ",password) # if user.check_password(password): # print(user.check_password(password)) # return user if str(user.password) == str(password): print(12345,user) return user except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a non-existing user (#20760). UserModel().set_password(password) It's always showing incorrect password although passwords are same and It's printing out 12345 and user also but it is not returning user. -
Raise MultiValueDictKeyError by request.FILES to get base64 image data
Actually i need to get base64 image data generated by croppie javascript library. The image data look like below. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAgAElEQVR4Xs1dB5xU1dX/39em7c422GXpVZGmWACxImAviYnYY/1UjLF8iYkxxq4xlk+jscZek1iiiUajRiMWehEFAemwLGyfnfravd/v3Dd39zEsxpYyuO7szKv3f8r/nHvueQz/5a9NmzbFMu32KF/ju4JrIwX8XbkQ9WCoFEKU+55fLsBrOBcQnLX6QksLwdOciw7XE43cxwqmsRWciRUJs2bF5MkD8v/Nt8z+2y5uwYIt8Wg0ewDApmoMU4XAHgA0IQQAAfrlc3qvXgK+z8E5hy8EPMEgePCZ4LQHAxcCgtFvxoXgSwDxtg/xNi/zPzxm771z/01j8B8HRAhhLFmyZoLvO1M5F9MMQ5ukaZplmTo0Lbg8AoN+aNADQDT5N2MMmqbJzz3Pg0eAMID7vAgSAcfg+6ILGIlS8eX7vsO4PzuZMN+2DOPvEyaMnccY8/+TAP3HAPnkk8+HeZ44njEczzmfKEeu+KJBNgxA14IBJ2lnNNCcNIGkXpeA6HrwO/hcwBUeCp4jD6UxHa7nw3NpfOk4OmzHCY4JwLJ0xGMxdLa3orY6gdbWZlFRmZyTy2RfjOjm83vvv//G/wQw/3ZAPv109XDOxZVC4DTGmElSHpijbk0wDB2mGQDi+R503ZDmSpolj0MzTKkR9LfEkUChYzAyWb7UEAIgncmisqIanZ2dsG1XnqNffR0K+Rxy2RS456J/fR+0tjbBcWxYuiHNHQBX+PxpnbFf73PIISv/ncD82wD5/POG8a7rXsUY+w75BJJ8Jd0k/TSenPvyt2WZEMKBYWiIx2NdGkDgWZaFznSn1A4CynVd5HI5pDpTyOUyyKQ7kMsV0NHRAcfxkc3kYJgG6uv7Y9y4sXQSNGxaj2GD+iPb0Y5sLovy6t5IpTKoqqyAU7AJe4ADOrkd7rwshPjVxEMPXfDvAOZfDsiyZev6AM5vfC5m+L4Px3Hg2LYUbDIdJM00qLbtwLZt5PN5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2FrEjh844l+MPbz8OJZVHTK4nekQE4ZNRx6GsNQ9SLdGVze/JbdP2lpqpLCIojW6oRasBVlpgAiUaj8Fy+sibdPm70jBlUjbHDa6eAfPbJJ9dms5lrKBLnxcIBJphkSWqwv0iaw0xI2X3l0NVFKtNGx1HapgY3DI4yJbQfbae0UdFedTzNpOSkD803EdEttGQaYdZwvL/0Dcxa/xx4TQE5cNhpDeNqpuGk8ReitzcYHlq6TFZYYNQ1hK8vnC0u1ZiwGVMjrdI6ASAxWaTh+P7Ppx9zxC1fGpAlc5fs4rr5pbqpRbjMmPoBY/E4GA+qRIiYBFIRnmFTMyH0WVCaE3bWYbMUdphKc3YGcKlzDWuoMhlSgjUypwKaTzOLOrJ+BxpSG/C3j15DZCDDitQC2FYKum9gj+T+mLHHuahy+sBmlFHojlGUxocBCfsudR89aUXpZ0pYaHaTfK7vUe7NTdsuG3Xk947cYcaxRw35ePbsxznnZwTRdHeJjpztL5nkCT Here is my HTML <form action="{% url 'profile' %}" enctype="multipart/form-data" method="post" class="pic-upload-form" id="form">{% csrf_token %} <div class="custom-file"> {% bootstrap_form form %} </div> <!-- Croppie area --> <div id="upload-demo"></div> <input type="hidden" id="image-data" name="imagebase64"> <button type="button" class="btn btn-outline-info btn-custom upload-result">save</button> </form> The last portion of my js where i bind the image data to a hidden input. $('.upload-result').on('click', function (ev) { $uploadCrop.croppie('result', { type: 'base64', size: 'viewport' }).then(function (src) { console.log(src); // bind the image data to the hidden inpu id image-data $('#image-data').attr('src', src); $('#form').submit(); }); }); And here is my view def user_profile_view(request): '''Handle the image of the user.''' if request.method == 'POST': form = UploadPicForm(request.POST, request.FILES) if form.is_valid(): profile = form.save(commit=False) # get the base64 image data profile.image = request.FILES['imagebase64'] profile.save() messages.success(request, 'your pic updated successfully.') return HttpResponseRedirect(reverse('learning_path_tracker:home')) else: # form's user field populated by current user form = UploadPicForm(initial={'user': request.user}) return render(request, 'users/uploadpic.html', {'form': form}) I think the image data is not a string that's why request.FILES raise error. But how can i solve this, thanks in advance. -
How to solve Unknow Field Error in Django
I am building a project a project by Django 2.0.2. What I want to do is making one of the fieldsets in admin page change automatically according to the database. Here is part of my code: models.py class Product(BaseModel): number=model.IntergerField("Food", null=True, blank=True, help_text="Food") @property def number(self): return 10 #just return a number for testing admin.py class ProductAdmin(admin.ModelAdmin): list_display=("number") fieldsets=(('<h1>Food</h1>'), {'fields':('number')}) When I refresh the admin page, it shows "Unkown fields (number) specified for Product. Check fieldset attribute of class ProductAdmin". I am new to Django and not sure about what goes wrong. In the admin.py, I have added "number" field but the error still exist. How can I solve it? Many Thanks and Happy New Year. -
Maintain concurrency in the user session
BY A NOVICE PROGRAMMER: Web application is being used with RFID card reader (as keyboard emulator). When the user scans the RFID card in the specific field, RFID reader pastes the card number and then hits enter by itself so that the form is submitted. Sometimes the user scans the card once and the reader detects it 2 times (contacted vendor but the reader does not support redetection delay kind of a thing). So on the backend, I have a view function which is executed when the user's form is submitted. From the view function, the card number is send to other 2-3 functions in order to complete all the processes. I checked the app logs and found that When the card is read 2 times, only 7-8 lines of code is being executed and before the condition is checked, due to scanning card 2nd time, the same functions are called again and the condition checking does not makes sense. What is the technical term which I should google in order to execute all the functions one by one without any interruption? Tried using conditions but did not work -
TypeError an invalid keyword argument for this function
Happy new year! ) i am newbie in Python trying to make forms field and have a problem My forms shows correctly at html but when i am trying to submit data and save it to db i have an error TypeError at /srdb/ 'send_date' is an invalid keyword argument for this function here is my code models.py class Srdb(models.Model): send_date = models.DateField() send_weight = models.IntegerField(default=0, validators=[MaxValueValidator(10000), MinValueValidator(100)]) track_code = models.CharField(default=None, blank=False, max_length=20) send_index = models.IntegerField(default=None, blank=False, validators=[MaxValueValidator(999999), MinValueValidator(100000)]) sender_fullname = models.CharField(default=None, blank=False, max_length=150) sender_dob = models.DateField() sender_adress = models.CharField(default=None, blank=False, max_length=400) receiver_index = models.IntegerField(default=None, blank=False, validators=[MaxValueValidator(999999), MinValueValidator(100000)]) receiver_fullname = models.CharField(default=None, blank=False, max_length=150) receiver_adress = models.CharField(default=None, blank=False, max_length=400) sender = models.ForeignKey(Dostavshik, on_delete=models.CASCADE, default=None, blank=False) def __str__(self): return str(self.id) forms.py class SrdbForm(forms.Form): send_date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), label='Дата Отправки') send_weight = forms.IntegerField(initial=0, validators=[MaxValueValidator(10000), MinValueValidator(100)], label='Отправленный Вес (граммы)') track_code = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'placeholder': 'Код Отслеживания Посылки'}), label='Трек Код') send_index = forms.IntegerField(validators=[MaxValueValidator(999999), MinValueValidator(100000)], widget=forms.TextInput(attrs={'placeholder': 'Индекс Почты Отправления'}), label='Индекc Отправления') sender_fullname = forms.CharField(max_length=150, widget=forms.TextInput(attrs={'placeholder': 'Отправитель'}), label='ФИО отправителя') sender_dob = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), label='Дата Рождения Отправителя') sender_adress = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'placeholder': 'Полный Адрес Отправителя'}), label='Адрес отправителя') # Получатель receiver_index = forms.IntegerField(validators=[MaxValueValidator(999999), MinValueValidator(100000)], widget=forms.TextInput(attrs={'placeholder': 'Индекс Почты Получения'}), label='Индекс Получателя') receiver_fullname = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Получатель'}), label='ФИО Получателя') receiver_adress = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'placeholder': … -
"Path for saving emails is invalid: None" in django
my project was running correctly but after that I made few apps I start my work on previous app but I'm trying to send email this time I'm getting this error and I'm not able to understand what's the problem, I tried to get email and console and it's working but when I use EMAIL_BACKEND = django.core.mail.backends.smtp.EmailBackend I get this error, can someone help to figure it out what's the problemthis is image of error link -
django pwa is not loading block contents while service worker added
While I was working with django pwa library in one of my django project outlined as this tutorial. When I added serviceworker.js as they proposed the layout was loaded online and offline but contents inside block contents didn't load. Code is exactly they described. Didn't paste code somewhere as this is a large code and I was converting my project to PWA after fully production running. Thank you for your kind help. Let me know my mistakes. -
How to use different session id for same user across different django project
i have 2 django projects running on different domains. Both are using same database and same models. One project is in 2.7 and other project is in 3.7. when user login into one domain, it log out user from other domain. How i can restrict him to not logging user out from one domain on login into another domain ? -
Django Celery - Creating duplicate users due to mutiple workers
I am facing a weird issue with celery in production. Currently, the production server has 4 celery workers which handle all the tasks registered by my django app. No custom queues are defined. The workers are basically 4 separate supervisor conf files. Now, in my app I am handling facebook webhook data, and I want a user with a specific FacebookID to be only created once on my backend. But, recently I checked and found out that there are users who have the same FacebookID, which should not have happened. What happened I think was e.g. user with FacebookID 666 sent me a webhook data. Now, a task is created which will create a new user instance in my database with FacebookID 666. Now, before the user is created in my database, the user hits me with another data, which also created a task but under a different worker, and thus I got myself two users with the same FacebookID. Is there any way I can configure celery to handle a user with a specific FacebookID to create tasks only in ONE worker? Or have I completely misjudged the situation over here? -
What's the best way to send and receive data using django?
I'm building an e-commerce site (and very new to django and python), and upon the user completing his online order, I want: the order to be sent to my office computer, where a pop-up will notify me The pop up will have 2 buttons, one will be "print invoice" and the other will be "order fulfilled" on pressing "order fulfilled", the django order model on the server will be updated so the specific order will be marked as "fulfilled". Is this doable? Is it too complicated? For step 1, I've read that sockets might be what I need to learn, but I don't know how it will work for step 3. Anyone have any suggestions?