Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make factory use `objects.create_user` instead of `objects.create` when creating model
Is there a way to make instantiating instances from factories use Model.objects.create_user instead of Model.objects.create? It seems that user_factory.create uses the latter, which makes the below code succeed even though username is a required field and not passed. @register class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User @pytest.fixture def new_user2(user_factory): return user_factory.create(first_name='abc') -
Debugging routing issue in Netbox plugin (Django)
I'm trying to debug a new plugin I'm writing for Netbox. But I'm currently stuck at the error. 'netbox_redfish' is not a registered namespace inside 'plugins' There is a stack trace but it isn't pointing to the line of code wich is causing the error. Error Code can be found here: https://github.com/accelleran/netbox_redfish Thanks -
Why Autocomplete form in django doesn't work
I have been trying several different kind of code for an autocomplte form with Django Im new on this but here are the code: Views.py def search_ifsc(request): try: q = request.GET.get('q', '').capitalize() search_qs = InfoTrabajadores.objects.filter(documento__startswith=q) results = [] print(q) for r in search_qs: dict_data = {'documento':r.documento,'nombres':r.nombres,'info':{ 'num_emergencia':r.num_emergencia, 'prov_salud':r.prov_salud, 'prov_salud_trabj':r.prov_salud_trabj, 'rh':r.rh}} results.append(dict_data) data = json.dumps(results) except Exception as e: data = 'fail'+ f'\n{e}' mimetype = 'application/json' return HttpResponse(data, mimetype) This in the endpoint to filter te data with the document Inside the document: <script type='text/javascript'> fetch('http://127.0.0.1:8000/ajax/search/') .then((response) => response.json()) .then((data) => { document.getElementById('nombre').value = data.nombres; document.getElementById('num_emergencia').value = data.num_emergencia; document.getElementById('prov_salud').value = data.prov_salud; document.getElementById('prov_salud_trabj').value = data.prov_salud_trabj; document.getElementById('rh').value = data.rh; } ) And the urls.py urlpatterns = [ path('ajax/search/' , search_ifsc, name='search_view'), ] This is how the site looks with the actual code I've been trying change de model and how the query works, but nothing change the response in the site -
how to add legend in django form
I am trying to add legend to the form field in my django project. But facing some issues unable to add the legend. Any kind of help will be appreciated. Form.py class MyForm3(ModelForm): class Meta: model = import fields = ['date_of_request', 'Number_of_units', 'Date_of_shipment', 'Required_doc',-------------- This should be the legend 'doc1', 'doc2', ] models.py class import(models.Model): date_of_request = models.DateField() Number_of_units = models.IntegerField() Date_of_shipment = models.IntegerField() Required_doc = models.CharField(max_length=200)---------- This should be the legend doc1 = models.BooleanField() doc2 = models.BooleanField() -
django how can i send data to def function in view.py when <a href is clicked
For example, I want to send data "1" when January is clicked January -
how to map data in column panda dataframe
Dataframe data I need to group each student/name by the teacher. Which I was able to do. Now I can't get the below desired output: Desired output Dataframe to map I want to output the data to this: { "name": "Roberto Firmino", "age": 31, "height": "2.1m" }, { "name": "Andrew Robertson", "age" : 28, "height": "2.1m" }, { "name": "Darwin Nunez", "age": 23, "height": "2.1m" } -
Broken migrations after implementing MultiSelectField with choices based on ForeingModel
I'm using MultiSelectField and it works perfect, the problem is when I need to do migrations after my models... class Title(models.Model): name = models.TextField(null = True) degree = models.TextField(null = True) class Person(models.Model): name = models.TextField(null = True) title = MultiSelectField(choices=Title.objects.values_list('name','degree'), max_choices=4, max_length=255, null = True, blank= True) The trick here is Person is trying to use Title before migrations happens, so it crashes. Instead of models.ForeignKey that actually take care about the dependent model. I've already tried to handle it with migration dependencies but it doesn't work. Any workaround? -
Django. I want it to be moved within that category list
I want it to be moved within that category list if I choose the previous and next text. Hi, everyone. English is not my first language. Therefore, please understand the poor expression in advance. But I dare you to understand this question and write it in anticipation of answering it. LOL (I used a translator for some content) I created a bulletin board app using DJango. These bulletins are categorized into categories. If you click on a text in the full list page, navigate to the detail page, and select Previous and Next, of course, it will move normally. What I've been struggling with for a few days is that when I click on a text in a particular category list and go to the detail page, I want it to be moved within that category list if I choose the previous and next text. ㅠ.ㅠ ** models.py ** from django.db import models from django.contrib.auth.models import User import os class Category(models.Model): name = models.CharField(max_length=20, unique=True) slug = models.SlugField(max_length=200, unique=True, allow_unicode=True) description = models.TextField(default='카테고리 설명') def __str__(self): return self.name def get_absolute_url(self): return f'/mytube/category/{self.slug}/' class Post(models.Model): title = models.CharField(max_length=100) hook_text = models.CharField(max_length=100, blank=True) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) … -
Creating one object for multiple models in one form
This is a project support a vendor. I have three models, Item DeliveryOrderForm TableList Item defines what items is sold by the vendor. DeliveryOrderForm saves the details of the recipient/buyer. TableList saves the details of each order's row that is ordered by the buyer. models.py class Item(models.Model): itemID = models.AutoField(unique=True,primary_key=True) itemPrice = models.DecimalField(default=0,max_digits=19,decimal_places=2) itemDescription = models.CharField(max_length=30) #deliveryorder status class Status(models.IntegerChoices): pending = 1 disapproved = 2 approved = 3 class DeliveryOrderForm(models.Model): deliveryOrderID = models.AutoField(unique=True,primary_key=True) vendorName = models.CharField(max_length=30) vendorAddress = models.CharField(max_length=200) recipientName = models.CharField(max_length=30) recipientPhone = PhoneNumberField(blank=False) recipientAddress = models.CharField(max_length=200) deliveryOrderStatus = models.IntegerField(default=Status.pending,choices=Status.choices) deliveryOrderDate = models.DateTimeField(default=timezone.now) class TableList(models.Model): deliveryOrderID = models.ForeignKey(DeliveryOrderForm,on_delete = models.CASCADE) itemID = models.ForeignKey(Item,on_delete=models.PROTECT) itemQuantity = models.IntegerField(default=0) So, in the admin page, creating an object of DeliveryOrderForm is fine. I was also able to display the DeliveryOrderForm along with the TableList. The issue now trying to create a view that works to CREATE an object of DeliveryOrderForm. I've tried this : forms.py class DOForm(ModelForm): class Meta: model = DeliveryOrderForm fields = '__all__' views.py def createDeliveryOrder(request): model = DeliveryOrderForm template_name = 'deliveryorder/create.html' deliveryOrderID = get_object_or_404( model.objects.order_by('-deliveryOrderID')[:1] ) formset = inlineformset_factory(DeliveryOrderForm,TableList, fields = [ 'itemID', 'itemQuantity', ]) if request.method == 'POST': form = DOForm(request.POST,prefix = 'deliveryorder') if form.is_valid() and formset.has_changed(): form.save() … -
How to push reviews from 3rd party website to Google and Facebook reviews venue page? (Django)
I have a website that collects reviews for a group of venues from their customers. I am looking at the feasibility for a user to automatically share their reviews on the venue's Facebook or Google page without having to retype it. Let's say I am User_1. I connect to website and leave a review for Venue_A. I would then be able to press a button that would atomically push my review to the Facebook and Google review against Venue_A page, without the user having to retype it. Does any know if this is something Google or/and Facebook have already in place? I can see some API about pulling reviews, but not much about pushing them. -
To apply 'update_session_auth_hash' in UpdateView
error occured at the code below. class UserUpdate(LoginRequiredMixin, UpdateView): model = User form_class = ProfileUpdateForm template_name = 'single_pages/profile_update.html' success_url = reverse_lazy('single_pages:landing') login_url = '/login/' def form_valid(self, form): u = form.save() if u is not None: update_session_auth_hash(self.request, u) return super(UserUpdate, self).form_valid(form) with the error message IntegrityError at /update/8/ UNIQUE constraint failed: single_pages_profile.phoneNumber Request Method: POST Request URL: http://127.0.0.1:8000/update/8/ Django Version: 3.2.13 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: single_pages_profile.phoneNumber Exception Location: C:\github\project\venv\lib\site- packages\django\db\backends\sqlite3\base.py, line 423, in execute Seems like it's related to the model Profile, which is OnetoOne with the user like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phoneNumberRegex = RegexValidator(regex = r'^01([0|1||6|7|8|9]-?([0-9]{3,4})-?([0-9]{4})$') phoneNumber = models.CharField(max_length=11, unique=True, validators=[phoneNumberRegex]) username = models.CharField(max_length=30) email = models.EmailField(max_length=50) address = models.CharField(max_length=200) Although I don't want Profile to be a ForeignKey of user, I tried that once but the same error occured. Lastly, this is forms.py class ProfileUpdateForm(UserCreationForm): phoneNumber = forms.CharField(required=False) address = forms.CharField(required=False) username = forms.CharField() email = forms.EmailField() password1 = forms.CharField() password2 = forms.CharField() class Meta(UserCreationForm.Meta): fields = UserCreationForm.Meta.fields + ('email',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].disabled = True def save(self): user = super().save() profile = Profile.objects.create( user=user, phoneNumber=self.cleaned_data['phoneNumber'], address=self.cleaned_data['address']) return user By the error message, problem is here: profile = … -
Dropdown are not working in Django , HTML
I am trying to display data from database throw drop-down list and Use filter query to filter data and display if i tried to select value of html and select but slot is not create. Debugging form and i see error. If i select anything but drop-down do't selected here is error Here is my code: slot/views.py def slot_create(request): form = SlotForm(request.POST) print(form) station = Station.objects.filter(user_id=request.user) print(station) if form.is_valid(): slot = form.save(commit=False) slot.user = request.user slot.save() messages.success(request, 'Your Slot is add successfully') return redirect('view_slot') return render(request, 'add_slot.html', { 'form': form, 'station': station }) here is my add_slot.html <form method="post" novalidate> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-12 mb-0"> {{ form.slot_name|as_crispy_field }} </div> <div class="form-group col-md-12 mb-0"> {{ form.per_unit_price|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.current_status|as_crispy_field }} </div> {% comment %} <div class="form-group col-md-6 mb-0"> {{ form.station|as_crispy_field }} </div> {% endcomment %} <div class="form-group col-md-6 mb-0"> <label for="station" class="block font-semibold text-sm mb-1"> Choose Station </label> <select name="station_name" id = "station"> {% for station in station %} <option value="{{station}}"> {{station}} </option> {% endfor %} </select> </div> <button type="submit" class="w-full rounded-full bg-red-gradient p-3 text-white font-bold hover:ring"> Add Slot </button> </div> </form> -
Django admin site foreign key
I have created some classes like STATE, DISTRICT, TALUK, and VILLAGE. Admin needs to add details in the admin panel. If the admin needs to add TALUK, he must select provided STATE, DISTRICT.I used a foreign key in the TALUK class for calling states and districts. But in admin after selecting STATE, the DISTRICT dropdown shows all the DISTRICTS. I need to get only the districts of that particular state This is the code I wrote in models.py class STATE(models.Model): state_name=models.CharField(max_length=25) def __str__(self): return self.state_name class DISTRICT(models.Model): district_state=models.ForeignKey(STATE,on_delete=models.CASCADE) district_name=models.CharField(max_length=25) def __str__(self): return self.district_name class TALUK(models.Model): taluk_state=models.ForeignKey(STATE,default=1,verbose_name="state",on_delete=models.CASCADE) taluk_district=models.ForeignKey(DISTRICT,on_delete=models.CASCADE) taluk_name=models.CharField(max_length=25) def __str__(self): return self.taluk_name class VILLAGE(models.Model): taluk_vill=models.ForeignKey(TALUK,on_delete=models.CASCADE) vill_name=models.CharField(max_length=25) def __str__(self): return self.vill_name -
Deploying Django on Windows server 2019 using xampp gives ModuleNotFoundError: No module named '_socket'\r
I am trying to host a django application on Windows Server 2019 using XAMPP and after going through all the settings necessary for the app to run, I get an Internal Server Error. Here's my setup: Running on venv, doing a pip freeze gives: (envcrm) DECRM@CRM2 MINGW64 /c/xampp/htdocs/crm $ pip freeze asgiref==3.6.0 Django==4.1.5 mod-wsgi==4.9.4 mysqlclient==2.1.1 sqlparse==0.4.3 tzdata==2022.7 Django App is in C:\xampp\htdocs\crm\decrm Directory Structure: C:\xampp\htdocs\crm |--decrm -> python project |--envcrm -> virtual environment |--mydecrm -> app |--static -> static folder for the apps |--templates -> templates folder for the apps |--users -> app Also placed MOD_WSGI_APACHE_ROOTDIR in the environment variables to be able to do a successful pip install mod_wsgi As for the httpd.conf, here's my setting for WSGI: LoadFile "C:/Users/DECRM/AppData/Local/Programs/Python/Python311/python311.dll" LoadModule wsgi_module "C:/xampp/htdocs/crm/envcrm/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp311-win_amd64.pyd" WSGIPythonHome "C:/xampp/htdocs/crm/envcrm" WSGIScriptAlias / "c:/xampp/htdocs/crm/decrm/wsgi.py" WSGIPythonPath "c:/xampp/htdocs/crm" <Directory "c:/xampp/htdocs/crm/decrm/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "c:/xampp/htdocs/crm/static/" <Directory "c:/xampp/htdocs/crm/static/"> Require all granted </Directory> with this, I get an Internal Server Error with these on the error logs: [Wed Jan 25 19:18:33.645848 2023] [wsgi:error] [pid 6720:tid 2060] [client ::1:51675] ModuleNotFoundError: No module named '_socket'\r [Wed Jan 25 19:18:33.694850 2023] [wsgi:error] [pid 6720:tid 2076] [client ::1:51674] mod_wsgi (pid=6720): Failed to exec Python script file 'C:/xampp/htdocs/crm/decrm/wsgi.py'., referer: … -
how to take data from the admin using Django forms?
I want when the user to select multiple users, a pop-up form will appear and he can send emails after submitting the form to the selected users This is admin.py ` class ReplyForm(forms.Form): message = forms.CharField(widget=forms.Textarea) @admin.register(ContactUs)class ContactUsAdmin(admin.ModelAdmin):actions = ['reply_by_email']list_display = ("id", "first_name", "last_name", "email","phone_number", "created_at", "message")search_fields = ("first_name", "last_name", "email", "phone_number", "message") def reply_by_email(self, request, queryset): if request.POST: form = ReplyForm(request.POST) if form.is_valid(): subject = "Custom email from admin" message = form.cleaned_data['message'] from_email = "admin@@example.com" recipient_list = [user.email for user in queryset] send_mail(subject, message, from_email, recipient_list) else: # check the form's errors print(form.errors) else: form = ReplyForm(request.POST or None) context = self.admin_site.each_context(request) context['form'] = form context['queryset'] = queryset return TemplateResponse(request, "reply_by_email.html", context) reply_by_email.short_description = "Send email to selected users" this is reply_by_email.html: {% load i18n %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" name="apply" value="Send Email"> </form> {% endblock %} when the admin fill the form nothing happens [enter image description here](https://i.stack.imgur.com/dAlaF.png) enter image description here Iam expecting a message from the user -
Azure Storage - FileNotFoundError: [Errno 2] No such file or directory
I am using django-storage to handle media files on Azure Storage. I am using Docker to deploy an app to Web App for Containers. When I am trying to run my celery task it gives me an error: File "/code/myapp_settings/celery.py", line 59, in test_task spec.loader.exec_module(spider_module) File "<frozen importlib._bootstrap_external>", line 839, in exec_module File "<frozen importlib._bootstrap_external>", line 975, in get_code File "<frozen importlib._bootstrap_external>", line 1032, in get_data FileNotFoundError: [Errno 2] No such file or directory: 'https://myapp.blob.core.windows.net/media/python/test.py' I checked Azure Storage and file with such name and path exists. I can access it from Azure and from URL normally without any issues. I can also upload and download file from admin panel. Below is my celery task that I am trying to run: @shared_task(name="test_task") def test_task(myapp_id): myapp = myapp.objects.get(id=myapp_id) python_config_file = myapp.python_config_file module_path = os.path.join(MEDIA_URL, f"{python_config_file}") spec = importlib.util.spec_from_file_location("myapp", module_path) myapp_module = importlib.util.module_from_spec(spec) sys.modules["myapp"] = myapp_module spec.loader.exec_module(myapp_module) asyncio.run(myapp_module.run( task_id = test_task.request.id )) return f"[myapp: {myapp_id}, task_id: {test_task.request.id}]" Below are my media variables that I have in settings.py DEFAULT_FILE_STORAGE = 'azure.storage_production.AzureMediaStorage' MEDIA_LOCATION = "media" AZURE_ACCOUNT_NAME = os.environ.get('AZURE_ACCOUNT_NAME') AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/' If anyone can tell me what am I doing wrong I'd be grateful. -
Celery Beat stuck on starting it
The Problem: I have issue with celery beat it only show starting on the terminal and not run any tasks also when I deploy it on heroku it do the same behavior. Here is the Terminal it only show starting: (shap-backend-venv) mahmoudnasser@Mahmouds-MacBook-Pro rest.shab.ch % celery -A server beat -l info --logfile=celery.beat.log --detach (shap-backend-venv) mahmoudnasser@Mahmouds-MacBook-Pro rest.shab.ch % celery -A server worker --beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler Secure redis scheme specified (rediss) with no ssl options, defaulting to insecure SSL behaviour. [2023-01-25 13:00:29,570: WARNING/MainProcess] Secure redis scheme specified (rediss) with no ssl options, defaulting to insecure SSL behaviour. [2023-01-25 13:00:29,571: WARNING/MainProcess] Secure redis scheme specified (rediss) Setting ssl_cert_reqs=CERT_NONE when connecting to redis means that celery will not validate the identity of the redis broker when connecting. This leaves you vulnerable to man in the middle attacks. -------------- celery@Mahmouds-MacBook-Pro.local v5.1.2 (sun-harmonics) --- ***** ----- -- ******* ---- macOS-12.6-arm64-arm-64bit 2023-01-25 13:00:29 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: server:0x106872730 - ** ---------- .> transport: rediss://127.0.0.1:6379/0 - ** ---------- .> results: rediss://127.0.0.1:6379/0 - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** … -
ModuleNotFoundError: No module named 'channels.http'
I found a couple of similar questions, but nothing really helped. I tried updating asgiref version and also updated channels and django-eventstream. I mainly followed the instruction from the django-eventstream-setup page. relevant packages from my setup: Package Version ------------------ --------- asgiref 3.6.0 channels 4.0.0 Django 4.1.2 django-eventstream 4.5.1 django-grip 3.2.0 django-htmx 1.12.2 gripcontrol 4.1.0 huey 2.4.3 MarkupSafe 2.1.2 requests 2.28.1 Werkzeug 2.2.2 The error I get upon executing python manage.py runserver: ... File "...\venv\lib\site-packages\django_eventstream\routing.py", line 2, in <module> from . import consumers File "...\venv\lib\site-packages\django_eventstream\consumers.py", line 7, in <module> from channels.http import AsgiRequest ModuleNotFoundError: No module named 'channels.http' I created an asgi.py file next to settings.py: import os from django.core.asgi import get_asgi_application from django.urls import path, re_path from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import django_eventstream os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'channels_test.settings') application = ProtocolTypeRouter({ 'http': URLRouter([ path("events/", AuthMiddlewareStack(URLRouter(django_eventstream.routing.urlpatterns)), { 'channels': ['test'] }), re_path(r"", get_asgi_application()), ]), }) In setup.py I updated for using asgi: WSGI_APPLICATION = "channels_test.wsgi.application" ASGI_APPLICATION = "channels_test.asgi.application" This is the folder structure: -
Graphene-Django - 'int' object has no attribute 'pk'
I'm new to working with GraphQL and Django and I am trying to test out in the playground but I am getting a 'int' object has no attribute 'pk' error. My models.py class Managers(models.Model): id = models.IntegerField(primary_key=True) jointed_time = models.DateField() started_event = models.IntegerField() favourite_team = models.ForeignKey( Teams, models.DO_NOTHING, db_column='favourite_team', blank=True, null=True) player_first_name = models.TextField() player_last_name = models.TextField() player_region_id = models.IntegerField() player_region_name = models.TextField() player_region_iso_code_short = models.TextField() player_region_iso_code_long = models.TextField() team_name = models.TextField() class Meta: managed = False db_table = 'managers' class Gameweeks(models.Model): id = models.IntegerField(primary_key=True) name = models.TextField() deadline_time = models.DateField() deadline_time_epoch = models.IntegerField() class Meta: managed = False db_table = 'gameweeks' class ManagerGwStats(models.Model): id = models.OneToOneField(Managers, models.DO_NOTHING, db_column='id', primary_key=True) active_chip = models.TextField(blank=True, null=True) gameweek = models.ForeignKey( Gameweeks, models.DO_NOTHING, db_column='gameweek') points = models.IntegerField() total_points = models.IntegerField() rank = models.IntegerField() rank_sort = models.IntegerField() overall_rank = models.IntegerField() bank = models.IntegerField() value = models.IntegerField() event_transfers = models.IntegerField() event_transfers_cost = models.IntegerField() points_on_bench = models.IntegerField() class Meta: managed = False db_table = 'manager_gw_stats' unique_together = (('id', 'gameweek'),) Schema.py class GameweekType(DjangoObjectType): class Meta: model = Gameweeks fields = "__all__" class ManagerType(DjangoObjectType): class Meta: model = Managers fields = "__all__" class ManagerGwStatType(DjangoObjectType): class Meta: model = ManagerGwStats fields = "__all__" class Query(graphene.ObjectType): all_managers = graphene.List(ManagerType) manager = … -
How to run the socket io server using gunicorn service
I'm using the socket.io service in my Django app, and I want to create one gunicorn service that is responsible for starting the socket.io service. Below is the socket io server code File name: server.py from wsgi import application from server_events import sio app = socketio.WSGIApp(sio, application) class Command(BaseCommand): help = 'Start the server' def handle(self, *args, **options): eventlet.wsgi.server(eventlet.listen(('127.0.0.1', 8001)), app) Below is the actual code of the server with connect, disconnect and one custom method File name: server_events.py from wsgi import application sio = socketio.Server(logger=True) app = socketio.WSGIApp(sio, application) @sio.event def connected(sid, environ): print("Server connected with sid: {}".format(sid)) @sio.event def disconnect(sid): print("Server disconnected with sid: {}".format(sid)) @sio.event def run_bots(sid): print("func executed") **# Here custom logic** When I hit python manage.py server in local, it will work fine, but on a production server, I don't want to type the python manage.py server command. What I want is to create one Gunicorn service and provide some instructions to that service so that when I hit the Gunicorn service command, it will start the socket IO server automatically, just like the runserver command. I tried to implement those things by creating the Gunicorn service file, but it couldn't work. socket-gunicorn.service [Unit] Description=SocketIO … -
Django - Filter same value with multiple dates
I'm having trouble selecting the first occurrence of the same value with multiple dates. I have the two following models in a logistic app: class Parcel(models.Model): """ Class designed to create parcels. """ name = models.CharField(max_length=255, blank=True, null=True) tracking_number = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) class ParcelStatus(models.Model): """ Class designed to create parcel status. """ SLA_choices = ( (_('Parcel shipped'), 'Parcel shipped'), (_('Delivered'), 'Delivered'), (_('In transit'), 'In transit'), (_('Exception A'), 'Exception A'), (_('Exception B'), 'Exception B'), (_('Exception C'), 'Exception C'), (_('Other'), 'Other'), (_('Claim'), 'Claim'), ) parcel = models.ForeignKey(Parcel, on_delete=models.CASCADE, blank=False, null=True) status = models.CharField(max_length=255, blank=True, null=True, choices=SLA_choices) event = models.ForeignKey(GridEventTransporter, on_delete=DO_NOTHING, blank=True, null=True) reason = models.ForeignKey(GridReasonTransporter, on_delete=DO_NOTHING, blank=True, null=True) date = models.DateTimeField(blank=True, null=True) I'm getting multiple statuses for a parcel. For example: Parcel Status Date XXXX Delivered 2022-22-12 13:00 XXXX Delivered 2022-15-12 18:20 XXXX Delivered 2022-12-12 15:27 XXXX Delivered 2022-12-12 15:21 XXXX In transit 2022-12-12 03:21 Inside my class, I'm retrieving parcels such as: def get_parcels(self): return Parcel.objects.filter(company=self.company) def get_parcels_delivered(self): parcels = self.get_parcels() parcels = parcels.filter(parcelstatus__status='Delivered', parcelstatus__date__date=self.date) parcels = parcels.distinct() return parcels My issue is the following: as you can see, I get multiple Delivered status with different dates. I would like to only retrieve the parcel with … -
SimpleJWT returns different access and refresh token each time
So, I have a django project, and have added JWT authentication. The problem is that each time I use TokenObtainPairView with the same credentials I get different access and refresh tokens. Is this the default behavior, as I have not changed anything in the settings? Is there a way to get the previous token unless it has expired? If you need more info please let me know. -
Command django-admin --version in windows terminal while using virtual environment displaying error
After installing Django version 1.9 in virtual environment using windows cmd command "django-admin --version" is displaying long error ending with the following: File "C:\Users\DELL\env\Lib\site-packages\django\db\models\sql\query.py", line 11, in from collections import Counter, Iterator, Mapping, OrderedDict ImportError: cannot import name 'Iterator' from 'collections' (C:\Users\DELL\AppData\Local\Programs\Python\Python311\Lib\collections_init_.py) Python is installed Virtual environment was activated. Django is installed using pip install django==1.9 What should I do run the command django-admin --version?? -
How to access environment variable in react?
I added react into django using webpack and when I created .env file in app_name/, I am trying to access environment variable like this process.env.base_url but I am getting undefined. file structure Django_React -- app_name -- src -- .env -- urls.py ... ... How can I create and access environment variable if react app is created like this ? -
Templates hmtl in view
I work under Django-python for the development of an application. For a few hours I have been stuck on the integration of html pages, let me explain: I can't associate several HTML pages under the same python class... class DieeCreateView(DieeBaseView, FormView): """View to create a Diee""" form_class = DieeForm template_name = 'diee_create.html' So I modified urls.py urlpatterns = [ path( "diee/new", diee_view.DieeCreateView.as_view(), name="diee_create", ), path( "diee/new/newthree", diee_view.DieeCreateView.as_view(), name="diee_create_03", ),] then make a list class DieeCreateView(DieeBaseView, FormView): """View to create a Diee""" form_class = DieeForm template_name = ['diee_create.html', 'diee_create_03.html'] but nothing works... Thanks in advance