Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to divide a huge model and group it with subdomains and keep a single modelForm
I am starting to do a project with Django and I have a very big Model that I would like to divide into sub-model it seems to me that it is possible according to the doc with models.ForeignKey but I don't know how to put them together in the same form This is my actual model and ModelForm class Device(models.Model): phone_regex = RegexValidator(regex=r'^[0-9]{10}$', message="Error: Format 0611223344") device_regex = RegexValidator(regex='^[a-zA-Z1-9]{3}$', message='Format de l\'identifiant invalide.') name = models.CharField(max_length=16) place = models.CharField(max_length=16) start_at = models.DateTimeField(default=datetime.datetime.now) end_at = models.DateTimeField(default=datetime.datetime.now) ChiefGo_function = models.CharField(max_length=16) ChiefGo_indicative = models.CharField(max_length=16) ChiefGo_phone = models.CharField(validators=[phone_regex], max_length=10) DChiefGo_function = models.CharField(max_length=10, blank=True) DChiefGo_indicative = models.CharField(max_length=10, blank=True) DChiefGo_phone = models.CharField(validators=[phone_regex], max_length=10) DSO_function = models.CharField(max_length=10, blank=True) DSO_indicative = models.CharField(max_length=10, blank=True) DSO_phone = models.CharField(validators=[phone_regex], max_length=10) device_id = models.CharField(max_length=3, validators=[device_regex], default=random_id) status = models.BooleanField(default=True) class DeviceForm(ModelForm): class Meta: ordering = ('end_at',) model = Device fields = ['name', 'place', 'start_at', 'end_at', 'ChiefGo_function', 'ChiefGo_indicative', 'ChiefGo_phone', 'DChiefGo_function', 'DChiefGo_indicative', 'DChiefGo_phone', 'DSO_function', 'DSO_indicative', 'DSO_phone', 'device_id', 'status'] widgets = { 'name': django.forms.TextInput(attrs={'placeholder': 'sairir le nom de l\'évenement'}), 'place': django.forms.TextInput(attrs={'placeholder': 'commune'}), 'start_at': django.forms.TextInput(attrs={'placeholder': 'date du début'}), 'end_at': django.forms.TextInput(attrs={'placeholder': 'date de fin'}), 'ChiefGo_function': django.forms.TextInput(attrs={'placeholder': 'fonction'}), 'ChiefGo_indicative': django.forms.TextInput(attrs={'placeholder': 'indivatif'}), 'ChiefGo_phone': django.forms.TextInput(attrs={'placeholder': '06 12 34 56 78'}), 'DChiefGo_function': django.forms.TextInput(attrs={'placeholder': 'fonction'}), 'DChiefGo_indicative': django.forms.TextInput(attrs={'placeholder': 'indivatif'}), 'DChiefGo_phone': django.forms.TextInput(attrs={'placeholder': '06 12 … -
How to concatenate text from multiple rows in to single record string Django
I'm doing some JOINS to get the data from the DB, but due to one column, my records are getting duplicated because of that column's unique values rest all other column values are the same. Below is an example of a sample record that I'm trying to achieve here: id name product_name 1 100 Cory Trimmer 2 100 Cory Steamer Now, I want the above record something like below: id name product_name 1 100 Cory Trimmer,Steamer Is there any way to achieve this kind of result as I have tried and exhausted all the links on the internet? Code which I'm using to get the records. products = ( customer.customerproduct_set.prefetch_related("product") .annotate( grade_code=F("product__grade__name"), package_type=F("product__packaging_type__packaging_type"), container_type=F("product__packaging_type__container_type"), product_name=F("product__name"), # this line is creating multiple rows ) .all() ) I know there is no such function available in Django to get this output. If anybody knows how to tame this kind of situation please suggest or highlight if I'm doing something wrong here. Any kind of help would be much appreciated. Thanks in advance! -
How to link two django models in a view
I am trying to design a app where some patient details are entered, an algorithm processes these, and directs to the appropriate treatment page I have managed to get it so patient details are entered and the user is the redirected to a view of that patient instance using the below code But I am not sure how to in TreatmentDetailView to instead present the details of the relevant treatment rather than that patient instance. models.py: class Patient(TimeStampedModel): # get a unique id for each patient - could perhaps use this as slug if needed patient_id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) name = models.CharField("Patient Name", max_length=255) age = models.IntegerField("Age", default=0) class Treatment(TimeStampedModel): name = models.CharField("Treatment Name", max_length=255) views.py: class PatientCreateView(LoginRequiredMixin, CreateView): model = Patient fields = ['name', 'sex', 'age'] def form_valid(self, form): form.instance.creator = self.request.user return super().form_valid(form) def get_success_url(self): return reverse('patient:detail', kwargs={"slug": self.object.patient_id}) class TreatmentDetailView(DetailView): model = Patient slug_field = “patient_id” def find_treatment(Patient): treatment_instance = runalgorithm(Patient) return treatment_instance urls.py urlpatterns = [ path( route='add/', view=views.PatientCreateView.as_view(), name='add'), path( route='<slug:slug>/', view=views.TreatmentDetailView.as_view(), name='detail'), ] -
How to not allow user to enter previous datetime in wagtail form?
I am working on a wagtail project (CMS based on Django). I have a DateTime field in one of the model page. from django.db import models from wagtail.core.models import Page class ArticlePage(Page): publish_at = models.DateTimeField() This field is shown on the Page edit screen. I want to add validations in the DateTime picker, which should not allow the user to pick past DateTime. Something like shown in the screenshot below: How can I achieve similar restriction? Is there a built in widget in django or wagtail, where I can add this validation? -
Django app gives an application error when deployed to Heroku
After deploying my django app to heroku while launching it I got an application error. "An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details." The application was working fine on localhost. Heroku logs showed the following: 2021-08-16T08:22:10.383324+00:00 app[web.1]: Traceback (most recent call last): 2021-08-16T08:22:10.383335+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/sit e-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2021-08-16T08:22:10.383336+00:00 app[web.1]: worker.init_process() 2021-08-16T08:22:10.383336+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/sit e-packages/gunicorn/workers/base.py", line 134, in init_process 2021-08-16T08:22:10.383336+00:00 app[web.1]: self.load_wsgi() 2021-08-16T08:22:10.383336+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/sit e-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2021-08-16T08:22:10.383336+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-08-16T08:22:10.383337+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/sit e-packages/gunicorn/app/base.py", line 67, in wsgi 2021-08-16T08:22:10.383337+00:00 app[web.1]: self.callable = self.load() 2021-08-16T08:22:10.383337+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/sit e-packages/gunicorn/app/wsgiapp.py", line 58, in load 2021-08-16T08:22:10.383337+00:00 app[web.1]: return self.load_wsgiapp() 2021-08-16T08:22:10.383338+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/sit e-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2021-08-16T08:22:10.383338+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-08-16T08:22:10.383338+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/sit e-packages/gunicorn/util.py", line 359, in import_app 2021-08-16T08:22:10.383338+00:00 app[web.1]: mod = importlib.import_module(module) 2021-08-16T08:22:10.383339+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/imp ortlib/__init__.py", line 127, in import_module 2021-08-16T08:22:10.383339+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-08-16T08:22:10.383339+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-08-16T08:22:10.383340+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-08-16T08:22:10.383340+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked 2021-08-16T08:22:10.383340+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in … -
Django ORM joining two models without primary key/foreign key relationships
I have been programming APIs with Django Rest Framework for a little while but have yet to need to invoke more complex joins than those made by default with the convenient PK/FK relationship building Django handles. One issue I seem to have is creating multi-level joins between models where the models do not have a primary-foreign key relationship. It is also impossible for the related fields themselves to be unique between the Customers and the source. from django.db import models class Customers(models.Model): address_key = models.CharField(db_column='address_key', max_length=40) lastname_key = models.CharField(db_column='lastname_key', max_length=5) firstname_key = models.CharField(db_column='firstname_key', max_length=4) fname = models.CharField(db_column='fname', max_length=255) lname = models.CharField(db_column='lname', max_length=255) address = models.CharField(db_column='address', max_length=255) city = models.CharField(db_column='city', max_length=255) state = models.CharField(db_column='state', max_length=255) zip = models.CharField(db_column='zip', max_length=255) class Meta: constraints = [ models.UniqueConstraint(fields=['address_key', 'lastname_key', 'firstname_key'], name='unique customer') ] class Attributes(models.Model): address_key = models.CharField(db_column='address_key', max_length=40) lastname_key = models.CharField(db_column='lastname_key', max_length=5) firstname_key = models.CharField(db_column='firstname_key', max_length=4) attr_1 = models.CharField(db_column='attr_1', max_length=255) attr_2 = models.CharField(db_column='attr_2', max_length=255) attr_3 = models.CharField(db_column='attr_3', max_length=255) An example of the SQL join I am interested in achieving using Django's ORMs is below. SELECT attr_1, attr_2, attr_3 FROM Attributes a JOIN Customers c ON c.address_key = a.address_key AND c.lastname_key = a.lastname_key AND c.firstname_key = a.firstname_key I've learned through the documentation and a … -
Formulate conditional Q on Unique Constraint for exception handling
Django doesn't throw a ValidationError because of a missing conditional in UniqueConstraint, and I don't know how to formulate a correct one. One of my models contains a unique constraint including a Foreign Key: class Entry(models.Model): """ Entry on a List """ name= models.CharField() expiration_date = models.DateField() list = models.ForeignKey(List, related_name="entries", on_delete=models.CASCADE) ... class Meta: constraints = [ UniqueConstraint(fields=['list', 'name'], name='unique_entry') # Each entry_name may only occur once per list. ] When submitting a new Entry which violates this constraint, the database rejects the query and Django throws an unhandled exception IntegrityError. According to the Django documentation this is intended behaviour: Validation of Constraints In general constraints are not checked during full_clean(), and do not raise ValidationErrors. Rather you’ll get a database integrity error on save(). UniqueConstraints without a condition (i.e. non-partial unique constraints) are different in this regard, in that they leverage the existing validate_unique() logic, and thus enable two-stage validation. In addition to IntegrityError on save(), ValidationError is also raised during model validation when the UniqueConstraint is violated. I would like your help with formulating a conditional, or other suggested solutions to fix this behaviour. The goal is to treat the UniqueConstraint like any other field that won't … -
There's an error in using filter to search company ,getting type errror can only concatenate str(Not nonetype) to str online compsearchobj in views.py
I'm using this definition to define the search and filter page using a database that is joined and saved. I have added views.py and models.py code for the same. views.py def multiplesearchcomp(request): if request.method=="POST": citycode=request.POST.get("citycode") statecode=request.POST.get("statecode") countrycode=request.POST.get("countrycode") revenue=request.POST.get("revenue") noofemployees=request.POST.get("noofemployees") domaincode=request.POST.get("domain_id") compsearchobj=DisplayCompanyDomain.objects.raw('select * from enquire_automation_app_displaycompanydomain where citycode="'+citycode+'" and statecode="'+statecode+'" and countrycode="'+countrycode+'" and domain_id="'+domaincode+'" and revenue="'+revenue+'" and noofemployees="'+noofemployees+'"') return render(request,'filtercompany.html',{"DisplayCompanyDomain":compsearchobj,"countries": Country_master.objects.all(), 'states': State_master.objects.all(), "cities": City_master.objects.all(), "domains": Domain_master.objects.all()}) else: compobj=DisplayCompanyDomain.objects.raw('select * from enquire_automation_app_displaycompanydomain') return render(request,'filtercompany.html',{"DisplayCompanyDomain":compobj, "countries": Country_master.objects.all(), 'states': State_master.objects.all(), "cities": City_master.objects.all(), "domains": Domain_master.objects.all()}) models.py class DisplayCompanyDomain(models.Model): companyname = models.CharField(max_length=100) address = models.CharField(max_length=200) citycode = models.CharField(max_length=20) statecode = models.CharField(max_length=20) countrycode = models.CharField(max_length=20) foundedin = models.CharField(max_length=20) revenue = models.CharField(max_length=100) noofemployees = models.CharField(max_length=20) domesticprojects = models.IntegerField(default=0) globalprojects = models.IntegerField(default=0) website = models.CharField(max_length=50) domain_id=models.CharField(max_length=20) no_of_projects=models.IntegerField() -
celery doesn't run task when I'm using Tweepy in Django
When I wanna use tweepy with celery tasks It doesn't run and it just give me failure tasks.py @shared_task(bind=True) def retweet(self, consumer_key, consumer_secret, access_token, access_token_secret, clean_text, clean_count, clean_lang, sleep_time): auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True) for tweet in tweepy.Cursor(api.search, q=(clean_text) + " -filter:mentions", count=clean_count,lang=clean_lang).items(int(clean_count)): tweet.retweet() views.py class Retweet(FormView): form_class = RetweetForm template_name = 'retweet.html' success_url = reverse_lazy('tweet:done') def form_valid(self, form): user = self.request.user query = form.cleaned_data.get('query') count = form.cleaned_data.get('count') time = form.cleaned_data.get('sleep_time') lang = form.cleaned_data.get('lang') clean_text = BeautifulSoup(query, "lxml").text clean_count = BeautifulSoup(count, 'lxml').text sleep_time = BeautifulSoup(time, 'lxml').text clean_lang = BeautifulSoup(lang, 'lxml').text retweet.delay(user.consumer_key, user.consumer_secret, user.access_token, user.access_token_secret, clean_text, clean_count, clean_lang, sleep_time) error: The full contents of the message body was: b'\x80\x04\x95B\x01\x00\x00\x00\x00\x00\x00(\x8c\x19crR6CW6AB9MpsLkFsGLu4i1du\x94\x8c2cMEZk1z8zlSPnKlYZKTgpBXEqeZ4EMpf4HGSIe7j1adYAAwf5w\x94\x8c21157597880-a3cBcPLXFNaaeT3DYbajBdznpdGid1llqqmxEE0\x94\x8c-LBmrhuR6MWIvJ1YhLpR9DDUIxlqBwumfbsMxlmZagZtC1\x94\x8cE\xd9\x87\xd9\x88\xd8\xb4 \xd9\x85\xd8\xb5\xd9\x86\xd9\x88\xd8\xb9\xdb\x8c OR \xd8\xa8\xd8\xb1\xd9\x86\xd8\xa7\xd9\x85\xd9\x87 \xd9\x86\xd9\x88\xdb\x8c\xd8\xb3\xdb\x8c OR \xd8\xa7\xdb\x8c\xd9\x84\xd8\xa7\xd9\x86 \xd9\x85\xd8\xa7\xd8\xb3\xda\xa9\x94\x8c\x013\x94\x8c\x02fa\x94\x8c\x016\x94t\x94}\x94}\x94(\x8c\tcallbacks\x94N\x8c\x08errbacks\x94N\x8c\x05chain\x94N\x8c\x05chord\x94Nu\x87\x94.' (333b) Traceback (most recent call last): File "/Users/User/PycharmProjects/twitterTest/venv/lib/python3.9/site-packages/celery/worker/consumer/consumer.py", line 581, in on_task_received strategy = strategies[type_] KeyError: 'tweet.tasks.retweet' -
save() missing 1 required positional argument: 'tran'
My save() method is throwing the error: save() missing 1 required positional argument: 'tran'. I overrode the save() method in the model “Transactions” as follows: def save(self,D,tran): self.DATE=D self.TYPE=tran.SERVICE_CODE self.SUCCESS=tran['Success'] self.TECHNICAL_DECLINES=tran['Technical_declines'] self.BUSINESS_DECLINES=tran['Business_declines'] self.TOTAL=self.SUCCESS+self.TECHNICAL_DECLINES+self.BUSINESS_DECLINES self.PERCENTAGE_TECH_DEC=((T/(self.TOTAL))*100) super(Transactions,self).save() where tran argument in the save() is a dictionary object passed on from views. Please note that I have also tried super(Transactions,self).save(D,tran) in the last line of save(). views.py def fetch(): DATE=datetime.datetime.now() print(DATE) status=Transactions.objects obj=wf() for tran in obj: print(tran) Transactions.save(DATE,tran) return Transactions.objects.all() Here wf() is a function retrieve database object from a model. From the output of print(tran) it is clear that the db_object is being fetched without any issue. output of print(): {'SERVICE_CODE': 'APY', 'Success': 1, 'Technical_declines': 0, 'Business_declines': 0} I don't understand where the argument tran is being missed. -
How to send custom JSON headers with requests in drf_spectacular (django)?
Can I create an custom description of JSON headers in drf_spectacular without using serializers class in @extend_schema decorator? -
how to load multiple images from json data - django
im trying to show multiple images in my template using ajax request every post has multiple images , but it takes some time to load images! class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) class Booking(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=40) my views.py def booking_detail_lists(request,id): obj = get_object_or_404(Booking,id=id) doc = Document.objects.filter(booking=obj) documents = [] for i in doc: documents.append({ 'source':i.docs.url }) data = { 'title':obj.title, 'admin':obj.admin.username, 'images':documents return JsonResponse({'data':data}) this is my script to load images , but its too slow to load images ! $.ajax({ type:'GET', url:"{%url 'booking:booking_detail_lists' id=2222 %}".replace(/2222/,{{obj.id}}), success:function(data){ if(data.data){ let images = data.data.images imgs = '' for(i=0;i<images.length;i++){ imgs +=` <img src="${images[i]['source']}" class="w-full" alt=""> ` console.log(images[i]['source']) } document.getElementById('images').innerHTML = imgs } } }) <div class="w-full md:w-6/12 mx-auto rounded-lg " id="images"> </div> and this is my url path('ajax/booking/<int:id>',booking_detail_lists , name='booking_detail_lists'), it load too slow ! is there a better way to load image data through ajax please ?! ` -
Django timezone models.DateTimeField does not have seconds via DRF
I have model which has DateTimeField class Genre(models.Model): pub_date = models.DateTimeField('date published',default=timezone.now) in database it has the Datetime with seconds 2021-07-27 07:51:18.87329 However when returning this in Django-Restful-Framework, it doesn't have seconds. like class GenreViewSet(viewsets.ModelViewSet): queryset = Genre.objects.all() serializer_class = GenreSerializer def list(self,request,*args,**kwargs): objs = Genre.objects.all() custom_data = { 'items': GenreSerializer(objs, many=True).data } return Response(custom_data) class GenreSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = ('id','pub_date') Somehow it shows like "pub_date": "07/27/2021 07:51P" Why seconds are omitted?? -
password authentication failed for user in django when using postgress
i have been trying to use the python-dotenvlibrary to work with my env variables. for other variables its working but when i came to use PostgreSQL in Django i am getting an error. This is what i am getting, conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: password authentication failed for user "brian" FATAL: password authentication failed for user "brian" Here is the code i am using if DEBUG: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('NAME'), 'USER': os.environ.get('USER'), 'PASSWORD': os.environ.get('PASSWORD'), 'HOST': os.environ.get('HOST'), 'PORT': os.environ.get('PORT'), } } any ideas -
Django Choicefield from a list
i have a small question about forms. So how i would usually create a choice form would be this way: Metric_name_CHOICES = [ ('Transfer', 'Transfer'), ('RFI/RFD', 'RFI/RFD'), ('...', '...') ] Metric_name = forms.ChoiceField(choices=correct_associate_action_CHOICES, widget=forms.Select) Which is a great method, but what if I wanted the list of choices to come from a list in a model? I guess something like: Metric_name = forms.ChoiceField(choices=dv_model.objects.get(Metric_name_dv), widget=forms.Select) So to take all the fields inside a column in a model, and display them as a drop down field. -
Using jQuery UI autocomplete input field in Django
I'm trying to create an autocomplete text input field in a ModelForm class, so I found jQuery UI library to do the autocomplete part of the input field, and this is what i did so far but it didn't work with me, so could you please check it and help me out? This is my model.py file: class Frequency(models.Model): EN_frequency = models.CharField(max_length=100, null=True) def __str__(self): return self.EN_frequency class MedicinePrescription(models.Model): medicine = models.ForeignKey(Medicine, null=True, on_delete=CASCADE) prescription = models.ForeignKey( Prescription, null=True, on_delete=SET_NULL) frequency = models.ForeignKey(Frequency, null=True, on_delete=CASCADE) This is my urls.py file: path('CreatePatientPrescriptionForm/<int:pk>/', views.CreatePatientPrescriptionFormView.as_view(), name='CreatePatientPrescriptionForm'), This is my views.py file: class CreatePatientPrescriptionFormView(CreateView): template_name = 'MedCareApp/patientPrescription-form.html' model = Prescription form_class = PatientPrescriptionForm def get_frequency_list(request): if 'term ' in request.GET: queryset = Frequency.objects.filter( EN_frequency__istartswith=request.GET.get('term')) titles = list() for frequency in queryset: titles.append(frequency.EN_frequency) return JsonResponse(titles, safe=False) return request def get_form_kwargs(self): kwargs = super().get_form_kwargs() random_user = User.objects.get(id=1) kwargs.update({ 'medicine_choices': get_medicine_list(random_user), 'frequency': self.get_frequency_list() }) return kwargs This is my template.html file: <script> $( function() { $( "#id_frequency" ).autocomplete({ source: '{% url '+CreatePatientPrescriptionForm+' %}' }); } ); </script> This is my forms.py file: class PatientPrescriptionForm (ModelForm): frequency = forms.CharField() class Meta: model = MedicinePrescription fields = ['frequency'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['frequency'].widget.attrs.update( {'class': 'text-field small w-input', … -
How to show the first true element after if condition in for loop in django template?
I have a for loop in Django template. After that, I check for coincidences. But in some cases, there are might be 3 coincidences. I need to show only the first coincidence. Now, my code returns the name for 3 times, because, there are 3 coincidences {% for ip in ips %} {% if d.name == ip.name %} <strong>{{ d.name}} </strong> {% endif %} {% endfor %} -
how i get image location with url using Generic API view in response in django rest framework
How i get image location with full url models.py class UploadImage(models.Model): img_id = models.AutoField(primary_key=True) image = models.ImageField(upload_to='images/') def __str__(self): return str(self.image) serializers.py class UploadedImageSerializer(serializers.ModelSerializer): class Meta: model = UploadImage fields = [ 'img_id', 'user_id', 'image', -
django runserver : relation "django_migrations" already exists
I have a django project source code, which includes several apps. The source code have been run successfully on one environment, but when transplanted to another device, with the same postgresql version(9.4.4), python version(2.7.5), and django version(1.8.5), but the runserver reports errors like this. The database has been imported in advance. return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "django_migrations" already exists -
I get this error Application Error in Django Heroku HOW to solve it?
my gunicorn : web: gunicorn https://serene-atoll-07314.herokuapp.com/ --log-file - 2021-08-16T11:29:39.421911+00:00 heroku[web.1]: Starting process with command gunicorn learning_logs.wsgi --log-file - 2021-08-16T11:29:41.369052+00:00 app[web.1]: [2021-08-16 11:29:41 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-08-16T11:29:41.369655+00:00 app[web.1]: [2021-08-16 11:29:41 +0000] [4] [INFO] Listening at: http://0.0.0.0:41765 (4) 2021-08-16T11:29:41.369730+00:00 app[web.1]: [2021-08-16 11:29:41 +0000] [4] [INFO] Using worker: sync 2021-08-16T11:29:41.373634+00:00 app[web.1]: [2021-08-16 11:29:41 +0000] [9] [INFO] Booting worker with pid: 9 2021-08-16T11:29:41.377020+00:00 app[web.1]: [2021-08-16 11:29:41 +0000] [9] [ERROR] Exception in worker process 2021-08-16T11:29:41.377021+00:00 app[web.1]: Traceback (most recent call last): 2021-08-16T11:29:41.377022+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2021-08-16T11:29:41.377022+00:00 app[web.1]: worker.init_process() 2021-08-16T11:29:41.377022+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 134, in init_process 2021-08-16T11:29:41.377022+00:00 app[web.1]: self.load_wsgi() 2021-08-16T11:29:41.377023+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2021-08-16T11:29:41.377023+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-08-16T11:29:41.377023+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-08-16T11:29:41.377024+00:00 app[web.1]: self.callable = self.load() 2021-08-16T11:29:41.377024+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2021-08-16T11:29:41.377024+00:00 app[web.1]: return self.load_wsgiapp() 2021-08-16T11:29:41.377024+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2021-08-16T11:29:41.377025+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-08-16T11:29:41.377025+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/util.py", line 359, in import_app 2021-08-16T11:29:41.377025+00:00 app[web.1]: mod = importlib.import_module(module) 2021-08-16T11:29:41.377025+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/importlib/init.py", line 127, in import_module 2021-08-16T11:29:41.377025+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-08-16T11:29:41.377026+00:00 app[web.1]: File "", line 1006, in _gcd_import 2021-08-16T11:29:41.377026+00:00 app[web.1]: File "", line 983, in _find_and_load 2021-08-16T11:29:41.377026+00:00 app[web.1]: File "", line 965, … -
Djang Rest JWT token creation on authorization
How to to be with registration of new users, when we use Django with JWT Token Authentification? They can't have any ways to make any POST request ever... -
How to apply pagination in this case (Django Rest Framework)?
I built a simple social media application. Users can post two types of posts Blog and Carousel. Users can follow other users, you can see other users posts if you follow them. So, while implementing the home page API (home page consists of both blog and carousel posts of people you follow) i filter out the blog and carousel like this. blogposts = BlogPost.objects.filter( Q(author__profile__in=request.user.profile.followings.all()) | Q(author=request.user) ) carouselposts = Carousel.objects.filter( Q(author__profile__in=request.user.profile.followings.all()) | Q(author=request.user) ) It basically filters all blogs and carousel of the people you follow and return it after applying suitable serializers. But the problem is when the page is loaded, if a user has got 100 posts in his home page all of them are loaded at once. Instead i only wany to load 10 recent posts in the beginning and keep loading next 10 recent posts when user reaches the bottom of the home page. Since there are two tables here Blogpost and Carousel i don't how to paginate this. Also, one more question? If i somehow paginate this content to send 10 recent posts at once, will it be internally querying only 10 posts at each request or will it query all 100 posts at … -
Django webcam html cannot render text
I'm working on a webcam web app using Django. I can load the webcam to the correct path, but I need to add some title and text in that path. I used this HTML but this renders only the webcam stream without the title and text. <html> <head> <title>Card player test</title> </head> <body> <h1>Card player test</h1> <img src="{% url 'card_player' %}"></img> </body> </html> I also tried adding the container div but it also doesn't work. <html> <head> <title>Card player test</title> </head> <body> <h1>Card player test</h1> <div class="container"> <img src="{% url 'card_player' %}"> </div> </body> </html> I see many tutorials and SO answers using same HTMLs, what did I do wrong? -
Upload images inside nested serializers in django rest framework
How can i upload images when user is trying to create announcement. I need to upload images to my computer and assign them to the announcement that he is trying to create. Models.py class Announcement(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) address = models.CharField(max_length=100) photo = models.ManyToManyField(Photo, blank=True) def nameFile(instance, filename): return '/'.join(['images', str(instance.name), filename]) class Photo(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to=nameFile, blank=True, null=True) Views.py class AnnouncementCreate(CreateAPIView): permission_classes = [IsAuthenticated] queryset = models.Announcement.objects.all() serializer_class = AnnouncementSerializer def perform_create(self, serializer): serializer.save(author=self.request.user) class PhotoViewSet(ListAPIView): queryset = models.Photo.objects.all() serializer_class = PhotoSerializer def post(self, request, *args, **kwargs): file = request.data.get('image') image = models.Photo.objects.create(image=file) return HttpResponse(json.dumps({'message': "Uploaded"}), status=200) Serializers.py class AnnouncementSerializer(serializers.ModelSerializer): parameters = ParameterSerializer(many=True, required=False) photo = PhotoSerializer(many=True, required=False) class Meta: model = Announcement fields = ['id', 'name', 'address', 'date', 'price', 'description', 'author', 'parameters', 'photo'] class PhotoSerializer(serializers.ModelSerializer): class Meta: model = Photo fields = ('name', 'image') -
Django, Apache2 and Mod_WSGI serves data slower than a fax miachine
I have a very basic Django instance set up on a RPi model 3. Important as this may indeed be the issue. I'm using Django 3.2, Python 3.7, Mod_WSGI, compiled from source against this version of python and Apache2, installed via the package manager (apt install apache2). Being unfamiliar with the back-end side of things in terms of Python and WSGI, I suspect maybe my set up is the issue... but I digress. Mod_WSGI is set up in daemon mode: LoadModule alias_module /usr/lib/apache2/modules/mod_alias.so WSGIScriptAlias / /home/pi/steve/steve/steve/wsgi.py WSGIProcessGroup steve WSGIDaemonProcess steve python-home=/home/pi/steve/env python-path=/home/pi/steve processes=2 threads=15 #WSGIPythonHome /home/pi/steve/env #WSGIPythonPath /home/pi/steve LogLevel debug <VirtualHost *:80> ... Django collects data from a PSQL database, orders it and serves it using return JsonResponse(JSONDataSorted, safe=False) For now all I am serving is this raw JSON. Its only 700 rows in the format: [{"T": "Sun Aug 15 21:51:35 2021", "C": 17.0, "RH": 81.5},...] Everything works completely as expected but it is PAINFULLY slow. Checking the request timing, 65ms is spent connecting, 59.29 SECONDS spend waiting and 15ms receiving. If I only return a single row, the time decreases to 30s waiting. Running the queries natively in PSQL with \timing on, the results are returned in 2 or …