Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add frontend to my backend project (django - Flutter)
how to add frontend (Flutter) to my back this is my backend the project is my django project and store is my django app backend -
CSRF-token error in django+nginx+gunicorn in docker
I have a problem with CSRF-token error in django+nginx+gunicorn in docker: Origin checking failed - http://185.255.132.54:5000 does not match any trusted origins. Such problem on live production server and this problem with dev local server: Forbidden (403) CSRF verification failed. Request aborted. This error appears only with NGINX port (any POST form, login page too (example.com/admin) (5000 for production and 8001 on dev server), but it's ok on gunicorn port (no static). I read some that I have to add CSRF_TRUSTED_ORIGINS = ['http://185.255.132.54:5000', 'http://185.255.132.54', 'https://185.255.132.54:5000'] to production server, but it didn't help. Here's my code: https://github.com/endlessnights/DjangoDockerNginxSample (all files, included Dockerfile, docker-compose, project files etc are there) What have I to do with such problem? -
Django admin get value of selected date range in filter
I wanted to get value of selected date range (from_date, to_date) in Django admin. Here is sample code. list_filter = (('last_login', filters.MyDateTimeFilter),) class MyDateTimeFilter(DateFieldListFilter): title = 'date filter' parameter_name = 'date_range_filter' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def queryset(self, request, queryset): print(queryset.GET.get('date_range_filter')) return queryset -
TabularInline for through Model not showing on Django 3
First off, I am using Django 3.2.9. Here are my models, pretty straightforward: class AChallenge(models.Model): name = models.CharField(max_length=255, unique=True) class SubAdvanced(models.Model): name: str = models.CharField(max_length=255, unique=True) challenges = models.ManyToManyField( AChallenge, related_name = 'challenge', through='SubAdvancedChallenge') class SubAdvancedChallenge(models.Model): sub_advanced = models.ForeignKey( SubAdvanced, on_delete=models.CASCADE) challenge = models.ForeignKey( AChallenge, on_delete=models.CASCADE) percentage = models.FloatField( validators=[MinValueValidator(0), MaxValueValidator(1)]) Here is my admin : class SubAdvancedChallengeInline(admin.TabularInline): model = SubAdvancedChallenge extra = 1 class SubAdvancedAdmin(BelleEmpreinteAdmin): inlines = (SubAdvancedChallengeInline,) admin.site.register(SubAdvanced, SubAdvancedAdmin) According to every single tutorial I see on the internet, I should be getting a nice inline editor like this: Despite all this, I am only getting this: If I try to force the inclusion of the "challenges" field, like this: class SubAdvancedAdmin(BelleEmpreinteAdmin): fields = ("name", "challenges") inlines = (SubAdvancedChallengeInline,) I will get the following error: (admin.E013) The value of 'fields' cannot include the ManyToManyField 'challenges', because that field manually specifies a relationship model. The fact that my TabularInline simply does not appear definitely seems like a bug, but it seems too crazy that this slipped through the cracks for so long. Anybody else met this issue? -
Model a 6-digit numeric postal code in django
I would like to define a 6-digit numeric postal code in Django models.py. At first, I tried this; postal_code = models.PositiveIntegerField(blank=False) However, postal codes can have leading zeros such as 000157. PositiveIntegerField is not suitable for it. If I use CharField, the field can accept alphabets which are not valid for postal codes. How do I define a 6-digit numeric postal code in django models.py? I am using Django v4. -
pyreadstat expected str, bytes or os.PathLike object, not InMemoryUploadedFile
Trying to make endpoint that can read uploaded .sav (SPSS) file and create model with data from it. For getting data from it I'm using pyreadstat library. But now when I'm trying to run it I have an error expected str, bytes or os.PathLike object, not InMemoryUploadedFile How I can change this code so pyreadstat can correctly read the given file? from rest_framework import generics, status import pandas as pd import pyreadstat from rest_framework.response import Response from .models import Research, Data from .serializers import FileUploadSerializer, SaveFileSerializer class UploadFileView(generics.CreateAPIView): serializer_class = FileUploadSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) file = serializer.validated_data['file'] df, meta = pyreadstat.read_sav(file, user_missing=True) json_df = df.to_json(orient='table') rsch = Research.objects.get(pk=1) Data.objects.create(research=rsch, data={}) -
How to define positive integer field that accepts 6 digits only in Django?
I want to define a database field in models.py that accepts only 6 digits in Django. This is how I define the field in models.py but it can accept any positive integer; six_digit_code = models.PositiveIntegerField(blank=False) I am using Django v4. -
How can i send my template values to database using Jquery, Ajax in django?
1.jquery $(textbox).on('click','.save',function(e){ e.preventDefault(); var x = $('#input_msg').val(); $.ajax({ url:'newpostx/', type: $(this).attr('method'), data: x, headers:{ 'X-CSRFToken':'{{csrf_token}}' } }).done(function(msg) { document.location = "http://127.0.0.1:8000/newpostx/" alert("save data") }).fail(function(err){ alert('no data was saved') }) }); home.html $(container).on('click','.show', function () { //On click of link, textbox will open console.log(count[1]) msg_bubble = 1; $("div.popup").show(); var num = $(this).attr('value'); console.log(num,'num') $(textbox).append('Grid No_ '+ num +'Bot MessagesType any text here Add Message BubbleSelect InputText InputButtonsStar RatingsCalendar & TimeImage/File InputSelect User Input: Name -->Type Input:File UploadTake PhotoFile Upload & Take PhotoButton Add ButtonNumber of stars:345Steps in stars:0.51Type Input:NameFull NameEmailMobilePasswordCustom TextCalendarData Limitation TypeAbsolute DateRelative DateMin DateMax DateTimeAppointment Duration15 minutes30 minutes1 hour2 hourStart Time09:00 AM10:00 AM11:00 AM12:00 AMEnd Time09:00 AM10:00 AM11:00 AM12:00 AMCancelSave') $("#input_msg").val() $("#input_msg"+num).text(window.localStorage.getItem(key+num)) console.log(count[num-1]) for(var i=2; iType any text here'); $(".container_inside").append(structure); $("#add_msg_"+num+i).text(window.localStorage.getItem(num+i)); } }); 3.views.py def post_new(request): if request.method == "POST": new_poll= text() #call model object d= request.POST new_poll.message= d['message'] new_poll.save() print(new_poll) return render(request, "loggedin.html") 4.models.py class text(models.Model): message = models.TextField(max_length=250) time = models.DateTimeField(default=datetime.now) 5.urls.py path('newpostx/',views.post_new,name='post_new'), -
"Error: Couldn't find that app. › › Error ID: not_found." when running heroku commands in console
Heroku sees my app in the list of apps, but I can't access it with any commands. I constantly getting the error "Couldn't find that app". I tried all these: heroku run python manage.py migrate -app my-api heroku run python manage.py migrate heroku run python manage.py createsuperuser -app my-api Although when I try to run commands for 'heroku apps' in my console, says I have one app called my-api. I followed other similar questions and tried the git remote commands beforehand but still failed. Example: heroku apps heroku git:remote -app my-api -
"Failed building wheel for psycopg2==2.8.6" - MacOSX using virtualenv and pip
I need install psycopg2==2.8.6 because when I installed latest version I get UTC error. I solve UTC error with install psycopg2==2.8.6 in my manjaro os but i try install this in my macOS and i got this: ld: warning: directory not found for option '-L/usr/local/opt/openssl/lib/' ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command '/usr/bin/clang' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for psycopg2 -
Django DetailView page - inline formset not saved in SQL
I am trying to implement Django inline formset to my DetailView. According to documentation it is much better to separate Detail and Form views and bring them back together in the third view and this is what I did. My form is visible in my template file but after submission, nothing happens. It is returning correctly to my product detail view but no data is saved to SQL. Can you please let me know what am I doing wrong? models.py class Product(models.Model): title = models.CharField('title', max_length=400, blank=False, null=False, help_text='max 400 characters', default='') class CERequest(models.Model): author = models.CharField(max_length=255, blank=True, null=True) related_component = models.ForeignKey(CostCalculator, on_delete=models.CASCADE, blank=True, null=True, default=1) number_of_units = models.IntegerField(default=0) related_product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True, related_name='related_product_ce_request') created = models.DateTimeField(default=timezone.now) total_price = models.IntegerField(verbose_name='Price (€)', default=0, blank=True, null=True) forms.py class CalculatorFormProduct(forms.ModelForm): author = forms.CharField(widget = forms.HiddenInput(), required = False) number_of_units = forms.IntegerField(help_text='Only numeric values are allowed.', min_value=0) total_price = forms.IntegerField(widget = forms.HiddenInput(), required = False) created = forms.DateTimeField(widget = forms.HiddenInput(), required = False) class Meta: model = CERequest fields = ('author', 'created', 'related_product', 'related_component', 'number_of_units') CalculatorFormsetProduct = inlineformset_factory(Product, CERequest, form=CalculatorFormProduct, fields=('author', 'related_product', 'related_component', 'created', 'number_of_units'), extra=3, can_delete=False) views.py class ProductView(LoginRequiredMixin, DetailView): model = Product template_name = 'hubble/ProductDetailView.html' def get_success_url(self): return reverse('product', kwargs={'slug': … -
how can i py my icons in my webapp in a better position?
i'm working with django-python making a webapp, but i have a problem, i have 4 icon in my first row and two icons under them, the problem is, above the lower icons are attached to the upper icons, this is the home.html file: {% extends 'dashboard/base.html' %} {% load static %} {% block content %} <section class="container text-center"> <h3>Welcome</h3> <hr> <br> <div class="row"> <div class="col-md-3"> <a href="{% url 'notes' %}"> <div class="card"> <img class="card-img-top" src="{% static 'images/notes.jpg' %}" alt="Notes image"> <div class="card-body"> <h5 class="card-title "> Notes </h5> Create Notes to refer them later. They are stored permanently until deleted </div> </div> </a> </div> <div class="col-md-3"> <a href="{% url 'homework' %}"> <div class="card"> <img class="card-img-top" src="{% static 'images/homework.jpg' %}" alt="Notes image"> <div class="card-body"> <h5 class="card-title "> Homework </h5> Add homeworks and assign them deadlines. They will be displayed prioritised by deadlines </div> </div> </a> </div> <div class="col-md-3"> <a href="{% url 'youtube' %}"> <div class="card"> <img class="card-img-top" src="{% static 'images/youtube.jpg' %}" alt="Notes image"> <div class="card-body"> <h5 class="card-title "> Youtube </h5> Search Youtube and select your desired video to play it on youtube </div> </div> </a> </div> <div class="col-md-3"> <a href="{% url 'todo' %}"> <div class="card"> <img class="card-img-top" src="{% static 'images/todo.jpg' %}" alt="Notes … -
How to fix FileNotFoundError: [Errno 2] No such file or directory:? (HEROKU)
I am trying to push my Django + React app to heroku. I have configured the path for my static files at below in settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'app/laundryman_frontend/build/static') ] The build is successful when I push to heroku but when I run heroku run python manage.py collectstatic I get the error FileNotFoundError: [Errno 2] No such file or directory: '/app/laundryman_frontend/build/static' My guess is that, Heroku is not looking does not recognise the path that I have set for the static files. Kindly help me solve this issue -
How to run parallel tasking with celery django?
I am looking to run tasks in parallel with django celery. Let's say the following task: @shared_task(bind=True) def loop_task(self): for i in range(10): time.sleep(1) print(i) return "done" Each time a view is loaded then this task must be executed : def view(request): loop_task.delay() My problem is that I want to run this task multiple times without a queue system in parallel mode. Each time a user goes to a view, there should be no queue to wait for a previous task to finish Here is the celery command I use : celery -A toolbox.celery worker --pool=solo -l info -n my_worker1 -------------- celery@my_worker1 v5.2.7 (dawn-chorus) --- ***** ----- -- ******* ---- Windows-10-10.0.22000-SP0 2022-08-01 10:22:52 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: toolbox:0x1fefe7286a0 - ** ---------- .> transport: redis://127.0.0.1:6379// - ** ---------- .> results: - *** --- * --- .> concurrency: 8 (solo) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery I have already tried the solutions found here but none of them seem to do what I ask StackOverflow : Executing two tasks at the same time with … -
Matching data from two functions in django context?
I'm struggling with matching contexts in my django project. I want to insert a .annotate() queryset, perfectly in just a set variable. I know it sounds weird but it's the best as I can describe it. I tried using .filter(), as it makes sense to me logically, but it doesn't quite work. my views.py from django.shortcuts import render from django.db.models import Count from django.db.models import Sum from .models import Offer_general from .models import Offer_details import datetime # Create your views here. def offer_general_list(request): #queryset = Offer_general.objects.filter(status=1).order_by('-id') context = {} context["data"] = Offer_general.objects.filter(status=1).order_by('-id')#stuff from Offer_general context["test"] = Offer_details.objects.values('fk_offer_general_id').annotate(sum=Sum('fk_offer_general_id')) return render(request, "index_offers.html", context) def offer_general_details(request): context = {} context["data"] = Offer_details.objects.all() return render(request, "offer_detail.html", context) models.py from django.db import models from django.contrib.auth.models import User from django.db.models import Count STATUS = ( (0,"Inactive"), (1,"Active") ) class Offer_type(models.Model): type = models.TextField() class Meta: ordering = ['-type'] def __str__(self): return self.type class Offer_general(models.Model): offer_name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) status = models.IntegerField(choices=STATUS, default=0) type = models.ForeignKey(Offer_type, on_delete= models.PROTECT) class Meta: ordering = ['-id'] def __str__(self): return self.offer_name class Offer_localization(models.Model): localization = models.TextField() class Meta: ordering = ['-localization'] def __str__(self): return self.localization class Offer_details(models.Model): slug = models.SlugField(max_length=200, unique=True) localization = models.ForeignKey(Offer_localization, on_delete= models.PROTECT, default="Opole") … -
Getting TypeError: Form.__init__() missing 1 required positional argument: ‘request’ even though I have passed request in both GET and POST methods
I have a form, which I am initializing its field with some data passing to it from view in its __init__() method to be shown on front end, using HttpRequest object. Even though, I have passed the HttpRequest object named request in both GET and POST methods, I am still getting the following error on POST request: TypeError at /accounts/invite-user/cancel/ InviteUserCancelForm.__init__() missing 1 required positional argument: 'request' Error full details are: Traceback Switch to copy-and-paste view D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\views\generic\base.py, line 84, in view return self.dispatch(request, *args, **kwargs) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\contrib\auth\mixins.py, line 73, in dispatch return super().dispatch(request, *args, **kwargs) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\contrib\auth\mixins.py, line 109, in dispatch return super().dispatch(request, *args, **kwargs) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\views\generic\base.py, line 119, in dispatch return handler(request, *args, **kwargs) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\views\generic\edit.py, line 151, in post form = self.get_form() … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\views\generic\edit.py, line 39, in get_form return form_class(**self.get_form_kwargs()) … My forms.py is: class InviteUserCancelForm(forms.Form): invitations = forms.ChoiceField( widget=forms.RadioSelect, choices=(('test_invite','test_invite'),) ) def __init__(self, request: HttpRequest, *args, **kwargs): super (InviteUserCancelForm, self).__init__(*args, **kwargs) if "invitations" in args: self.fields['invitations'] = forms.ChoiceField( label="Your Invitations", widget=forms.RadioSelect, choices=request["invitations"] ) … -
Django ValueError when A field is empty
i have a ModelForm which is like this : Forms.py : class send_to_evaluatorForm(forms.ModelForm): class Meta: model = send_to_evaluator exclude = ('Creater_UserID','mozo1_id','mozo2_id','mozo3_id','knowledge') so the problem comes when i leave a field empty and submit to save it... but when everything is filled and nothin left empty the code runs ok. a part of my view : if request.method == "POST": form = send_to_evaluatorForm(request.POST) mozo3=request.POST.get('mozo3') mozo1=request.POST.get('mozo1') mozo2=request.POST.get('mozo2') if form.is_valid: obj = form.save() the error happens because the form doesnt validate and while i was debugging it i noticed that a field is required here is my model if you want to have a look...if i let nazar empty my form doesnt save it models.py: mozo1_id = ForeignKey(topic1,on_delete=models.PROTECT,blank=True, null=True) mozo2_id = ForeignKey(topic2,on_delete=models.PROTECT,blank=True, null=True) mozo3_id = ForeignKey(topic3,on_delete=models.PROTECT,blank=True, null=True) nazar = TextField(verbose_name='point_of_view',max_length=4000) create_date = IntegerField(default=LibAPADateTime.get_persian_date_normalized(), blank=True, null=True) Creater_UserID = ForeignKey(Members,on_delete=models.PROTECT,blank=True, null=True) knowledge = ForeignKey(TblKnowledge,on_delete=models.PROTECT,blank=True, null=True) def __str__(self): return str(self.id) -
Django - how get the average time of a person that answered
I would like to get the Average time of answers of each person. Model: class Person(models.Model): uid = models.UUIDField(default=uuid.uuid4, primary_key=True) first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) email = CIEmailField() class CoursePerson(models.Model): uid = models.UUIDField(primary_key=True, default=uuid.uuid4) course = models.ForeignKey( Course, related_name="courses_persons", on_delete=models.CASCADE ) person = models.ForeignKey( "Person", related_name="courses", on_delete=models.CASCADE ) created_at = models.DateTimeField(auto_now_add=True) start_at = models.DateTimeField() class CoursePersonPasswordFormSubmission(models.Model): uid = models.UUIDField(primary_key=True, default=uuid.uuid4) text_mask = models.CharField(max_length=255) text_length = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) course_person = models.ForeignKey( CoursePerson, related_name="password_submissions", on_delete=models.CASCADE ) I've started to write the the def_queryset function. Everything on the beginning is ok since I have to filter stuff before do that logic: def get_queryset(self): accounts = get_account_ids(self.request) course_person_queryset = CoursePerson.objects.filter( account__in=accounts, is_in_analytics=True, status__gte=CoursePerson.StatusChoices.OPEN, course__type="form" ) course_person_queryset = filter_base_analytics( self.request, course_person_queryset, date_start=self.request.GET["date_start"], date_end=self.request.GET["date_end"], ) ...I'm blocked here... But now, I have to render a list of person with their Average of delay of response. Means, the initial message time sent to the user is course_person__start_at and the answer time of the person is password_submissions__created_at what I've tried: person_queryset = models.Person.objects.filter( courses__in=course_person_queryset.values_list('uid', flat=True), courses__password_submissions__created_at__isnull=False, courses__emails_person__opened_at__isnull=False, ).annotate( first_password=Subquery( CoursePersonPasswordFormSubmission.objects.filter( course_person_id=OuterRef("uid") ) .order_by("created_at") .values("uid")[:1] ), ) But this can't work as a person can have multiple course_person. and these course_person can have multiple … -
Visual Studio Code Automatically adds useless code
enter code hereI recently switched to VSC, installed python, pylance plugins. Everything seemed to be working fine, but when I started working with django, vsc started automatically when selecting an option in views.py CBV including Optional: str etc, for example context_object_name: Optional[str] Here I click Enter And then it automatically adds I don't want to remove hints in the code and automatic addition, but I also don't want him to add unnecessary -
Django Authentication Login From Active directory
How can I authenticate and login the user from Active Directory? This is my code Authenticate.py: from .models import User from ldap3 import ALL, Server, Connection, NTLM from ldap3.core.exceptions import LDAPException from django.contrib.auth.backends import ModelBackend def validate_user_credentials(username, password): server = Server(host='@xxxDomain', use_ssl=False, get_info=ALL) try: with Connection( server, authentication="NTLM", user=f"{''}\\{username}", password=password, raise_exceptions=False, ) as connection: print(connection.result['description']) return True except LDAPException as e: print(e) return False class UserAuth(ModelBackend): def authenticate(self,request,username=None,password=None,**kwargs): try: if (validate_user_credentials(username, password)): print("Helloooooooooooooo") user = User.objects.get(username=username) print(user) return user return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(username=user_id) except User.DoesNotExist: return None views.py: class UserLoginView(View): form_class = UserLoginForm def get(self, request): form = self.form_class return render(request, 'login/login.html', {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): cd = form.cleaned_data userexistindb = User.objects.filter( username=cd['username'], is_user_local=False).exists() username = cd['username'] password = cd['password'] try: if userexistindb: try: user = authenticate( request, username=username, password=password) if (user is not None): login(request=request, user=user) messages.success( request, 'Loged in success', 'success') return redirect('login:result') else: messages.error(request, 'us', 'warning') except User.DoesNotExist: messages.error( request, 'Invalid User/Password', 'warning') except User.DoesNotExist: username = None messages.error( request, 'Invalid User/Password', 'warning') return render(request, 'login/login.html', {'form': form}) The result is the sessionid It is created,The username and password are correct and the … -
Migrations Error in Django: AttributeError: 'str' object has no attribute '_meta'
I know this has been asked before. But, I tried the available solutions. Those don't seem to work in my case unless I missed something unintentionally. I dropped all the tables/relations from the connected database and deleted all the previous migration files except the init.py. And then ran the makemigrations command which worked fine. But got this error after running migrate. Here is the error: Applying book.0001_initial... OK Applying reader.0001_initial...Traceback (most recent call last): File "/home/brainiac77/github/bookworms_backend/backend/manage.py", line 22, in <module> main() File "/home/brainiac77/github/bookworms_backend/backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 290, in handle post_migrate_state = executor.migrate( File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/executor.py", line 131, in migrate state = self._migrate_all_forwards( File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/executor.py", line 163, in _migrate_all_forwards state = self.apply_migration( File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/executor.py", line 248, in apply_migration state = migration.apply(state, schema_editor) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/migration.py", line 131, in apply operation.database_forwards( File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/operations/models.py", line 93, in database_forwards schema_editor.create_model(model) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 440, in create_model if field.remote_field.through._meta.auto_created: AttributeError: 'str' object has no attribute '_meta' reader.0001_initial.py # Generated by … -
is there any python or django package that contains all address?
A few years ago I was working with a package for addresses, that package includes region, countries, states, cities, areas, sub areas...etc. It contains great data and all data connected together, but unfortunately I forgot it and what it's name. Now I spent a lot of hours to find it or any other library that contains the same info, but no results. anyone can help me by suggest a library, not apis no google maps. many thanks in advance. -
How to use AND in Django?
This is in my views.py win = Bid.objects.filter(auction__closed=True) f = Bid.objects.get(user=request.user) I want to do this foo = Bid.objects.filter(auction__closed=TRUE AND user=request.user) How to achieve this in django? -
Gunicorn Django response statusText missing
I have a Django DRF/React setup using React and JWT for authorisation. On local runserver, I send the request for token, I recieve access and refresh tokens. When the access token expires, I have an Axios interceptor set which checks the error response and sends new response with refresh token. All passes and works fine. if ( error.response.data.errors[0].code === "token_not_valid" && error.response.status === 401 && error.response.statusText === "Unauthorized" ) { I noticed on server (Gunicorn), that the process all works fine, access token received and works as expected until expiry, but the refresh token request doesn't even send. Then after some debugging I noticed the gunicorn server sends the same response but without statusText. I am only assuming it is something to do with Gunicorn as that is the only difference than running code on runserver locally. On image, Left side is local response. Right side is server response. Any reason I would not receive the statusText? Any setting I need to be aware of? -
How to get a specific id for my task in Django?
I have a django app in which I log in as an admin and add a tasks for a specific employee. Then I log in as the employee and I have to end the task when it's done. I display my active tasks in an table in a html template and I want to make the ended task is_active = 0 to check that the task is done. I also want to store the date when the task was done in closed_at. My models.py: class Employee(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) objects = models.Manager() address=models.TextField() created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now_add = True) active_tasks = models.IntegerField(default = 0) completed_tasks = models.IntegerField(default = 0) daily_r = models.IntegerField(default = 0) weekly_r = models.IntegerField(default = 0) monthly_r = models.IntegerField(default = 0) annual_r = models.IntegerField(default = 0) class Tasks(models.Model): id = models.AutoField(primary_key=True) employee_id = models.ForeignKey(Employee,blank=True,null=True,on_delete=models.CASCADE) is_active = models.IntegerField(default = 1) headline = models.CharField(max_length = 100) body = models.TextField() created_at = models.DateTimeField(auto_now_add = True) assigned_at =models.DateTimeField(auto_now_add = True) closed_at = models.DateTimeField(auto_now_add = True) My views.py def viewActiveTasks(request): current_user = request.user current_user_id = current_user.id employees = Employee.objects.filter(user_id = current_user_id) user_employees = User.objects.filter(is_employee=1) tasks = Tasks.objects.filter() return render(request, "employees_active_tasks.html", {'employees':employees,'user_employees':user_employees,'tasks':tasks}) def endTask(request): employee=Employee.objects.get(user_id=request.user) …