Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        Django forms.py phone number charfield only accept number/integer, I did it but the validation error not working, go to def validate(self)my forms.py from django import forms from .models import Account FRUIT_CHOICES= [ ('Afghanistan', 'Afghanistan'), ('Albania', 'Albania'), ('Algeria', 'Algeria'), ('Andorra', 'Andorra'), ('Angola', 'Angola'), ('Antigua and Barbuda', 'Antigua and Barbuda'), ('Argentina', 'Argentina'), ('Armenia', 'Armenia'), ('Australia', 'Australia'), ('Austria', 'Austria'), ('Azerbaijan', 'Azerbaijan'), ('Bahamas', 'Bahamas'), ('Bahrain', 'Bahrain'), ('Bangladesh', 'Bangladesh'), ('Barbados', 'Barbados'), ('Malaysia', 'Malaysia'), ] class RegistrationForm(forms.ModelForm): password=forms.CharField(widget=forms.PasswordInput()) confirm_password=forms.CharField(widget=forms.PasswordInput()) phone_number=forms.CharField(widget=forms.TextInput(attrs={ 'placeholder':'Enter Phone Number' })) country=forms.CharField(widget=forms.Select(choices=FRUIT_CHOICES)) email=forms.EmailField(help_text="We'll never share your email with anyone else") class Meta: model=Account fields=['first_name','last_name','email','phone_number','password'] def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['first_name'].widget.attrs['placeholder']='Enter First Name' self.fields['last_name'].widget.attrs['placeholder']='Enter last Name' self.fields['email'].widget.attrs['placeholder']='Enter Email' self.fields['password'].widget.attrs['placeholder']='Enter Password' self.fields['confirm_password'].widget.attrs['placeholder']='Repeat Password' for abc in self.fields: self.fields[abc].widget.attrs['class']='form-control' def clean(self): cleanned_data=super().clean() password=cleanned_data.get('password') confirm_password=cleanned_data.get('confirm_password') enter image description here if password != confirm_password: raise forms.ValidationError("Password and confirm password does not match") **def validate(self): cleanned_data=super().clean() phone_number=cleanned_data.get('phone_number') if phone_number.is_number() == False: raise forms.VallidationError("Please enter valid phone number, Example=012111111")** okay, regarding this function def validate(self): #this is working, the charfield only accept integer cleanned_data=super().clean() phone_number=cleanned_data.get('phone_number') if phone_number.is_number() == False: raise forms.VallidationError("Please enter valid phone number, Example=012111111") Supposedly I shall get the error when the phone number contain alphabet "Please enter valid phone number, Example=012111111" , right? But the output came out phone_number “gbfhbgf” value must be an integer. May I know any solution to edit this error? enter image description here
- 
        How to fix Django website showing 404 errors on all website links onlineso i recently uploaded a my first django website on cpanel . After uploading i realised the website is showing 404 errors on all website links ... let me show the links and urls `from .views.home import Index , shop, about urlpatterns = [ path('', Index.as_view(), name='homepage'), path('store', shop, name='store'), path('about-us', about , name='about-us'), ] ` The design of the website is supposed to automatically go to example.com/shop as the main page but its showing 404 errors instead so .views is a folder under shop app Need assistance on urls and how to correctly configure my website to show content after page load
- 
        RecursionError: maximum recursion depth exceeded while calling a Python objectI have a pretty large Django backend that runs perfectly fine on my Debian Linux server but always throws the following error on my local Windows machine: File "F:\Python\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1138, in _find_and_load_unlocked File "F:\Project\env\Lib\site-packages\imageio\plugins\__init__.py", line 54, in __getattr__ return importlib.import_module(f"imageio.plugins.{name}") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Python\Lib\importlib\__init__.py", line 117, in import_module if name.startswith('.'): ^^^^^^^^^^^^^^^^^^^^ RecursionError: maximum recursion depth exceeded while calling a Python object Can anyone tell me why this error only appears on my local windows machine? The error appears right after starting the server.
- 
        bootstrap offline not working, only via CDN [closed]<link rel="stylesheet" href="/csvtoppt/bootstrap-offline/css/bootstrap.css"> <script src="/csvtoppt/bootstrap-offline/js/bootstrap.bundle.js"></script> This is the bootstrap code I'm testing out, pulled directly from their webpage: <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown </a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link disabled">Disabled</a> </li> </ul> <form class="d-flex" role="search"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> </nav> local server complains the file is not found. I'm positive it is right there where I put it. I even right clicked and copied the path. Not Found: /csvtoppt/static/webpages/bootstrap-offline/css/bootstrap.min.css Not Found: /csvtoppt/static/webpages/bootstrap-offline/js/bootstrap.bundle.js [09/Dec/2022 21:46:53] "GET /csvtoppt/static/webpages/bootstrap-offline/css/bootstrap.min.css HTTP/1.1" 404 2890 [09/Dec/2022 21:46:53] "GET /csvtoppt/static/webpages/bootstrap-offline/js/bootstrap.bundle.js HTTP/1.1" 404 2893 I'm using the latest stable release of bootstrap 5.2.3 I've experienced this with another version of bootstrap (5.0.2) It works fine when I used bootstrap delivered via CDN I'm working on a Django project. I use Pycharm as …
- 
        intern_profile_view() missing 1 required positional argument: 'request'Can anyone tell me what I've done wrong? I'm trying to create a simple multi users app in django and I can quite tell what I'm missing in my view. Here's what I have so far. views.py @method_decorator([login_required, intern_required], name='dispatch') def intern_profile_view(request): if request.method == 'POST': user_form = InternSignUpForm(request.POST, prefix='UF') profile_form = InternProfileForm(request.POST, prefix='PF') if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) user.save() user.intern_profile.bio = profile_form.cleaned_data.get('bio') user.intern_profile.location = profile_form.cleaned_data.get('location') user.intern_profile.save() else: user_form = InternSignUpForm(prefix='UF') profile_form = InternProfileForm(prefix='PF') return render(request, 'interns/intern_profile.html',{ 'user_form': user_form, 'profile_form': profile_form, }) models.py class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_intern = models.BooleanField(default=False) class InternProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='intern_profile') bio = models.CharField(max_length=30, blank=True) location = models.CharField(max_length=30, blank=True) traceback Traceback (most recent call last): File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mikha\issue_env\lib\site-packages\django\utils\decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) TypeError: intern_profile_view() missing 1 required positional argument: 'request'
- 
        django import-export how to add foreing keyI am using django-import-export to import an excel to my model, what I do is that I create a form with some inputs from where it loads the file, then in form_valid() I process the file to load it to the database, the model has two foreign keys 'id_order' and 'gestion'; 'id_orden' comes in the excel and 'gestion' I get it with gestion= Gestion.objects.get(idgestion=obj.pk) which is the id of the form that I am saving, but what I want to know is how I can pass 'gestion' to ModelResource and then save it to the database view.py class GestionView(CreateView): model = Gestion form_class = GestionForm template_name = 'asignacion/gestion.html' success_url = reverse_lazy('asignacion_url:gestion') def form_valid(self, form): isvalid = super().form_valid(form) obj = form.save() gestion= Gestion.objects.get(idgestion=obj.pk) file = self.request.FILES['file'] item_gestion =ItemResourceResource() dataset = Dataset() imported_data = dataset.load(file.read(), format='xls') result = item_gestion.import_data(dataset, dry_run=True) if not result.has_errors(): item_gestion.import_data(dataset, dry_run=False) model.py class ItemGestion(models.Model): idgestion = models.AutoField(primary_key=True) numero_imagenes = models.CharField(max_length=45, blank=True, null=True) id_orden = models.ForeignKey('Asignacion', models.DO_NOTHING) aviso_sap = models.CharField(max_length=45, blank=True, null=True) poliza = models.CharField(max_length=45, blank=True, null=True) observacion_cierre = models.CharField(max_length=250, blank=True, null=True) gestion=models.ForeignKey('Gestion', models.DO_NOTHING) resources.py class ItemResourceResource(resources.ModelResource): id_orden = fields.Field(column_name='id_orden', attribute='id_orden', widget=ForeignKeyWidget(Asignacion,'id_orden')) class Meta: model = ItemGestion import_id_fields = ('id_orden',) exclude = ('idgestion', )
- 
        Django Ajax Dropdown Select2 not return dataThere is a dropdown form that I created with ajax. The form works without using the Select2 tag and returns data. But when I enter the select2 tag, it does not show the detail that should be displayed according to the selection. I use select2 for all select fields in the system. That's why I defined the select2 tag on my layout template like this. <script> $('.select').select2({ allowClear: true }); </script> Here is my ajax code : <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_worksite_id").change(function () { const url = $("#subunitForm").attr("data-subunit-url"); const worksiteId = $(this).val(); $.ajax({ url: url, data: { 'worksite_id': worksiteId }, success: function (data) { $("#id_upper_subunit_id").html(data); } }); }); Thank you for your help, best regards
- 
        Form fields not showing when including form templateThe form fields don't show when including form in another template. This is the form: class ClinicSearchForm(forms.Form): q = forms.CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['q'].label = 'Search for' self.fields['q'].widget.attrs.update( {'class': 'form-control'}) This is the template: <form method="get"> {{ form.as_p }} <input type="submit" class="btn btn-primary my-1" value="Search"> </form> And the view: def clinic_search(request): form = ClinicSearchForm results = [] if 'q' in request.GET: form = ClinicSearchForm(request.GET) if form.is_valid(): q = form.cleaned_data['q'] results = Clinic.objects.filter(name__icontains=q) context = { 'form' : form, 'results' : results, } return render(request, 'guide/clinic/clinic_search.html', context) I'm including the form with the include tag but I only get rendered the button, not the field. The form shows when in its own url, but not when included in another template (this other template has no other forms). What am I missing?
- 
        Website on Django . how to display similar products on the product card id page. As in the picture let's sayWebsite on Django . how to display similar products on the product card id page. As in the picture let's say models.py class Whatches(models.Model): id=models.AutoField(primary_key=True) title=models.CharField(max_length=250, verbose_name='Название') description=models.TextField(verbose_name='Описание',blank=True) collections=models.ForeignKey(Collections_watches, on_delete=models.CASCADE, verbose_name='Коллекция часов' ,blank=True,null=True,related_name='watches_collections') price=models.DecimalField(max_digits=7,decimal_places=0,verbose_name='Цена в рублях' ,blank=True ,null=True) image = models.ImageField( help_text='150x150px', verbose_name='Ссылка картинки') slug=models.SlugField(max_length=255,unique=True,db_index=True,verbose_name="URL") ` views.py def watch_card(request, watch_slug): watch_card = get_object_or_404(Whatches, slug=watch_slug) return render(request,'mains/about/catalog/watches/watch_card.html',context={ 'watch_card': watch_card, }, ) enter image description here
- 
        Introspect related model to determine name of attribute for reverse descriptor?Given schema: class User(models.Model): name = models.CharField(max_length=50) class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) User objects will end up having a post_set attribute of type: django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager Which returns a RelatedManager based on Post's default manager. Cool. Q: But if you're trying to introspect on a schema, how do you determine that the attribute name is "post_set"? When I call User._meta.get_fields(), I see a field called "post", not "post_set". (Of type: django.db.models.fields.reverse_related.ManyToOneRel) I've explored nearly all of ManyToOneRel's API, and can't find any attribute or method that will return the value "post_set", only "post".
- 
        NextJS using Django API - How to choose best patternI have GeoDjango running on a digital ocean droplet and I'm rewriting project from VueJs to NextJs hosted on Vercel. In Vue we have service pattern connected with store that is responsible for fetching and updating data. I figured out the fetching part which is quite good but I'm still trying to figure out the best way to update data. How should I construct the CRUD layer without using the NextJs API folder ( I don't want to have another backend calling my Django backend). Should I use context? Should I use middleware? Should I create custom services? How to call them then? Is there an equivalent of store in NextJs? I'm asking because I want to avoid cluttering as right now I'm using fetch POST on pages. I'm using NextAuth that gives me a context with jwt token. Thank you for any hints
- 
        navigations and dropdowns are very laggy on ios devices but work fine on android and windows. any Ideas?Django web app on Pythonenywhere, farhood.pythonanywhere.com, navigations and dropdowns are very laggy on ios devices but work fine on android and windows. any Ideas on what might cause this? I've searched online and did not find any relevant info
- 
        Document more than one repos with MkDocsI got a special situation where I have a few Django packages that work closely together, and I want to document them together at one place. medux-common: common used models, views, etc. medux: main application medux-online: web interface for certain functions medux-docs: the documentation package Both medux-online and medux use the common module, and I don't want to have 3 documentation homepages, but just one where all is documented at one place. Is there a possibility in MkDocs to "load" external packages? I use the mkdocstrings plugin to load the docstrings from my code. Its docs says, that the path must be set so that the module to document must be importable. In my medux-docs package, I import all the other packages using pip install -e ../medux etc., which works fine. But MkDocs does not find them: $ mkdocs serve [...] ERROR - mkdocstrings: medux.core.middleware could not be found ERROR - Could not collect 'medux.core.middleware' How do I do that? I don't want to merge all repositories into one, as medux and medux-online should be 2 pypi packages too. I just want MkDocs to find the imported medux, medux-online, and medux-common. Do I completely think the wrong way?
- 
        Django-Quill-Editor not rendering text into webpageI added Quill Editor to my admin panel to post blogs on my django project. But the text doesn't render. once I add the .html and |safe I get a parser error. If I remove the .html it just doesn't render. Any ideas? Strange thing is that this is working on my production server, but not local, which isn't ideal as I would like it working for testing. Here is the code im using: <body> <header>{% include 'navbar.html' %}</header> <div class="blog-container"> <div class="col-md-10" id="bloggrid1"> <div class="row"> {% for post in posts %} <div class="col-md-4" id="bloggrid2"> <div class="blog-post"> <div class="blog-content"> <img class="blog-img" src="{{post.blog_image.url}}" alt="My image" /> <h2 class="blog-title">{{post.blog_title}}</h2> <article class="blog-article"> <p>{{post.blog_article.html|safe}}</p> </article> <a href="{% url 'viewblog' post.id %}" class="btn btn-secondary" type="button" >Read More...</a > <p class="blog-date">Posted on: {{post.blog_date}}</p> </div> </div> </div> {% empty %} <h3>No Blog Uploads</h3> {% endfor %} </div> </div> </div> {% comment %} {% include 'footer.html' %} {% endcomment %} </body> </html>
- 
        Django: Can I change one request in the template and then call the view again? It shall be a loop betwen view and template where one attribute changesIn views.py I use a POST request that specifies the settings for the game. The game function starts the game with these settings. In the template, I want to call the game function again after every round and increase the value of the current round. So in the template I need to submit the form again with the same values from the former request and only increase the value of currentround. I tried to insert the same form in the template and fill it with the values that were put into the former form. Then, only change the value of the current round. Should I create a model for every game that is set up instead and increase the counter in there or is it possible to change the request from round to round for one attribute while maintaining all the other ones?
- 
        Is it possible to get N number of records per a value in a joined table WITHOUT multiple queries?So I have three tables: article_page - (for my articles) represented by the model Page article_page_category - glue table between article_page and article_category as they're many to many article_category - category information, represented by the model Category I want to make a query to the database that gets N number of records (10 to 20 probably) PER category, preferably in one query, as I can have a lot of categories at once, and this can be quite expensive. I've been trying all sorts of different types of queries and I'm having no luck - I've even tried various subqueries but that didn't translate amazingly well to Django, and raw sql queries were difficult to get working. To give an example: So let's say I have the categories of business, technology, sports I want to get 10 articles from business, 10 from technology, and 10 from sports - all of which are categories in article_category Is there a way to do that with one query? I've got something like this right now, but I really think this isn't the right approach: class GroupedArticleListView(APIView): def get(self, request): categories = Category.objects.filter(taxon=1) categories = categories.annotate( top_articles=Subquery( Page.objects.filter( category=OuterRef("pk") ).order_by("-date").values_list("id", flat=True)[:10].first(), output_field=IntegerField() ) ) The …
- 
        Django admin models not showing in productionI've put my django project into production. Every time a add an admin model it does not update and show on my admin panel. The migrations and collectstatic commands are all going through fine. I have tried to source a fix but I just can't get it to work. Works completely fine in local server. Here is my code although: models.py class PostImage(models.Model): image = models.ImageField(null=False, blank=False, upload_to="images", default="default.png") image_title = models.CharField(max_length=100, null=False, blank=False, default="") def __str__(self): return self.image_title class BlogPost(models.Model): blog_title = models.CharField(max_length=255, null=True, blank=True) blog_article = QuillField(null=True, blank=True) blog_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") blog_date = models.DateField(auto_now_add=True) def __str__(self): return self.blog_title class EnterImage(models.Model): enter_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") enter_image_title = models.CharField(max_length=100, null=False, blank=False, default="") def __str__(self): return self.enter_image_title class QuillPost(models.Model): content = QuillField() def __str__(self): return self.content class AboutMe(models.Model): about_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") about_image_title = models.CharField(max_length=100, null=False, blank=False, default="") def __str__(self): return self.about_image_title urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', include('martinhensonphotography.urls')), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT) admin.py from django.contrib import admin from . models import PostImage, EnterImage, …
- 
        Login page is showing errors on redirect instead of showing errors on loginI'm completely stumped here. So I copied and pasted this code from another project but on this project for some reason when I enter an incorrect user/pass combo it redirects to anther page then shows the errors there instead of just reloading the login page and displaying the errors there. On the other project, the view reloads the login view with the errors. I'm using Django 3.2 on both projects class LoginView(FormView): form_class = LoginForm template_name = 'users/forms/login.html' success_url = reverse_lazy('blog:index') def dispatch(self, request, *args, **kwargs): if self.request.user.is_authenticated: return redirect('blog:index') return super(LoginView, self).dispatch(request, *args, **kwargs) def form_valid(self, form): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(self.request, user) return redirect('blog:index') else: messages.error(self.request, "Your account is not active, please contact an administrator", extra_tags='alert alert-danger') else: messages.error(self.request, "Username/Password is invalid", extra_tags='alert alert-danger') return super(LoginView, self).form_valid(form) I am displaying the messages in the login template. The messages are working, they're just not reloading the login view, instead it takes me to the success url! What am I missing? This is literally the exact same code I'm using on another project and it's working as expected.
- 
        requests.get generates a continuous loop of the webhookI built a simple webhook listener in django. The webhook sends me a JSON. I am able to get all the info stored in the JSON correctly. Then I need to download locally an image file from url. from django.views.decorators.csrf import csrf_exempt import requests @csrf_exempt def webhook(request): if request.method == 'POST': print('Webhook received') # I extract all the information I need and I initialize an object received_data = get_all_data_from_json(request.body) x = requests.get(received_data.url) open("myimage.jpg", "wb").write(x.content) ..... ..... ..... return HttpResponse("Webhook received!") The problem is that the requests.get causes the webhook listener to loop endlessly. If I remove it, everything works just fine. Where am I wrong?
- 
        Cannot resolve keyword 'available_from_gte' into field. Choices are: available_from, available_till, id, room, room_idI have the following models. class Room(models.Model): room_number = models.PositiveSmallIntegerField( validators=[MaxValueValidator(1000), MinValueValidator(1)], primary_key=True ) class TimeSlot(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) available_from = models.TimeField() available_till = models.TimeField() Here is my views.py keys = ['room', 'available_from_gte', 'available_till_lte'] values = [room_obj, available_from, available_till] # room_obj contains object of Room model. available_from and available_till contains time in 02:00:00 format. parameters = {} for key, value in zip(keys, values): if value is not None and value !=[] and value != '': parameters[key] = value time_slots_list = TimeSlot.objects.filter(**parameters) On running the above code I get the following error. Cannot resolve keyword 'available_from_gte' into field. Choices are: available_from, available_till, id, room, room_id Can someone please help me with it?
- 
        Custom django data migration creating records allauth.account EmailAddress model returns error - django.db.migrations.exceptions.NodeNotFoundError:I am upgrading a django project that was created with the default django auth. Email verification was implemented with the django.contrib.auth.tokens package. The way it worked was that the 'is_active' flag of the default django user which itself is extended with a custom user is initially set to False and changes to True after the user verifies the email. Now, I have upgraded the project to use django-allauth, gotten every thing else to work just fine (in development), EXCEPT the email verification. Since django-allauth extends the User model with the EmailAddress model and checks 'verified' flag on this model to determine if an email has been verified/confirmed, I decided to write a custom data migration which creates the records in the EmailAddress table and sets verified = True if user.is_active = True. However, I get the error below: django.db.migrations.exceptions.NodeNotFoundError: Migration accounts.0003_create_allauth_email_records_for_existing_users dependencies reference nonexistent parent node ('allauth.account', '0002_email_max_length') accounts/migrations/0003_create_allauth_email_records_for_existing_users.py # Generated by Django 3.2.11 on 2022-12-09 10:56 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0002_delete_profile'), ('allauth.account', '0002_email_max_length') ] def create_allauth_email_records_for_existing_users(apps, schema_editor): UserModel = apps.get_model("accounts", "User") EmailMoldel = apps.get_model("allauth.account", "EmailAddress") for user in UserModel.objects.all(): email_record = EmailMoldel.objects.filter(email=user.email).first() if email_record == None: if user.is_active: email_verified = True else: email_verified …
- 
        Refreshing the offline pageI have been a problem for long time and i cant figure it out by my own. ı have a project that is coded in Django, project has some data in the SQL tables and there are some tables which are empty yet and the empty tables will be filled by the real date and time matches with the date and time which comes from SQL table. Some how i manage this if my site is open. in the code i have a little refresher funcktion like this; ``#The refresher function; function myFunction() { var x = document.getElementById("myDIV"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } window.setTimeout( function() { window.location.reload(); }, 60000); it works fantastic if the site is open in the browser but i neet it to work fine again if the website is not open in the browser. is there any way to manage that? thnx for helping...
- 
        How does django add to cart with ajax-jquery works?` my variable productid from ajax data below returns an empty string but my aim is to return product id from django sessions when user clicks the add-to-cart , <script> $(document).on('click', '#add-cart-btn', function (e) { e.preventDefault(); $.ajax({ type: "POST", url: "{% url 'storebasket:add_to_cart'%}", data:{ productid: $("#add-cart-btn").val(), csrfmiddlewaretoken: "{{csrf_token}}", action: "post" }, success: function(json){ }, error: function (xhr, errmsg, err) {} }); }) </script>` ` Here is the error raised: ` ` File "C:\Users\DELL\Documents\PROGRAMMING\VSCODE\PYTHON\ecommerce\storebasket\views.py", line 19, in add_to_cart product_id = int(request.POST.get('productid')) ValueError: invalid literal for int() with base 10: '' ` The view that raises the error: # capture ajax data def add_to_cart(request): basket =MySession(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product=get_object_or_404(Product, id=product_id) # save to MySession basket.add(product=product) response=JsonResponse({'test': 'data'}) return response My session creation code is as follows: class MySession(): def __init__(self,request): self.session=request.session basket=self.session.get('S_key') if 'S_key' not in request.session: basket=self.session['S_key']={} self.basket=basket #request.session.modified = True def add(self, product): """ Adding and updating the users basket session data """ product_id = product.id if product_id not in self.basket: self.basket[product_id] = {'price': str(product.price)} # save in the session self.session.modified = True class MySession(): def __init__(self,request): self.session=request.session basket=self.session.get('S_key') if 'S_key' not in request.session: basket=self.session['S_key']={} self.basket=basket #request.session.modified = True def add(self, product): """ Adding and …
- 
        'datetime.datetime' object has no attribute 'strip'I created an update form, the form has 2 time field and 2 date time field, once click on submit even nothing change, I got an error "'datetime.datetime' object has no attribute 'strip'". but there is no error when creating a new object for the same model . modles: time_start=models.DateTimeField(blank=True,null=True) htime_start=models.TimeField(blank=True,null=True) time_end = models.DateTimeField(blank=True, null=True) htime_end=models.TimeField(blank=True,null=True) time_require=models.DateTimeField(blank=True,null=True) machine=models.ForeignKey(Machine,null=True, on_delete=models.SET_NULL, blank=True) forms: class AssignTimeForProjects(forms.ModelForm): title = forms.CharField(disabled=True) owner=forms.CharField(disabled=True) time_require=forms.TimeField(disabled=True) class Meta: model = tb_order # fields='__all__' fields = ['title', 'owner', 'grade', 'quantity', 'time_require','htime_start','color', 'mould','time_start','time_end', 'htime_end' ,'machine'] def __init__(self, *args, **kwargs): super(AssignTimeForProjects, self).__init__(*args, **kwargs) self.fields["time_end"] = JalaliDateField(label=('تاریخ اتمام'), widget=(AdminJalaliDateWidget)) self.fields["time_start"] = JalaliDateField(label=('تاریخ شروع'), widget=(AdminJalaliDateWidget)) Html: <label>{{ form.htime_start.label}}</label> {% render_field form.htime_start type="time" class+="form-control timepicker" autocomplete="off" %} <br> <label>{{ form.time_end.label}}</label> {% render_field form.time_end class+="form-control" autocomplete="off" %} <br> <label>{{ form.htime_end.label}}</label> {% render_field form.htime_end type="time" class+="form-control" autocomplete="off" %}
- 
        Why .last()/.first() change the order of the ordered and distinct queryset?I have query like this - it needs to filter values by date and in case we have priorities on dates (x), we are setting up proper order which data we need. def filterX(self, order_list=[3,2,1], *args, **kwargs): return ( self.get_queryset() .filter(*args, **kwargs) .order_by( "date", Case( *[ When(x=y, then=Value(i)) for i, y in enumerate(order_list) ], default=None, ).asc(), ) .distinct("date") ) So I need only one item per one date with highest order given. And it works perfectly. From table 1 I have table 2 -> Table 1. ID DATE PRIORITY 1 2022/11/1 1 2 2022/11/1 2 3 2022/11/1 3 4 2022/11/2 2 5 2022/11/3 1 6 2022/11/3 2 Table 2. ID DATE PRIORITY 1 2022/11/1 3 4 2022/11/2 2 5 2022/11/3 2 But if I use this query for one date I get queryset with one item (which I need), but after .last the item is actually changed. Any advices?