Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NOT NULL constraint failed: statussaver_post.user_id
class post(models.Model): content=models.TextField(null=True,blank=True) title = models.CharField(max_length=200,null=True,blank=True) vedio = models.FileField(upload_to='vedios', blank=True, null=True) img = models.ImageField(upload_to='images', null=True, blank=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) def __str__(self): return self.title def userpost(request): if request.method=='POST': form=uploadform(request.POST,request.FILES) if form.is_valid(): form.save() return redirect('home') else: form=uploadform() return render(request,'statussaver/u.html',{'form':form,}) from django import forms from .models import post class uploadform(forms.ModelForm): class Meta: model=post fields= 'all' enter code here -
Django, connecting channels websocket with signals
I have a Channels web socket, I'm trying to add a signal from another app so when an event is created the WebSocket would send a message according to the logic it has. When I first connect the WebSocket the function runs properly, when I'm adding a new object of the sender model I get an error. consumer: class CameraOnlineConsumer(JsonWebsocketConsumer): def connect(self): self.accept() return self.send(json.dumps({"type": "websocket.accept", "send": "Connected Successfully"})), self.camera() def camera(self): result = self.check_events() print("new event") return self.send(json.dumps({ "type": "websocket.send", "send": result })) def get_events(self): return PastureEvent.objects.filter(result=8, farm_id='1', processed=False).order_by('-time_stamp')[:2] def check_events(self): minute_delta = timedelta(seconds=60) query_set = self.get_events() if not query_set: result = {'camera status': CameraOffline.default_detail, } return result elif len(query_set) == 1: # means that no new events has been recorded since last check. result = {'camera status': CameraOnline.default_detail, 'first time_stamp': str(query_set[0].time_stamp)} return result elif len(query_set) >= 2: # two relevant events received. difference = query_set[0].time_stamp - query_set[1].time_stamp if difference <= minute_delta: if query_set[1]: # query_set[1].processed = True & query_set[1].save() didn't work, why? PastureEvent.objects.select_for_update().filter(id=query_set[1].id).update(processed=True) else: pass # time difference between them is under/equal to the desired time difference between events. result = {'camera status': CameraOnline.default_detail, 'first time_stamp': str(query_set[0].time_stamp), 'last time_stamp': str(query_set[1].time_stamp)} return result else: if query_set[1]: PastureEvent.objects.select_for_update().filter(id=query_set[1].id).update(processed=True) else: pass … -
How to create a log database in django to record the user that created, updated or deleted an object?
I'm facing a difficulty recording the user in database who created, updated or deleted an object. I've found a simple solution with threadlocal and a logging abstract class that is not usually recommended here: Why is using thread locals in Django bad? . Here the main problem with this solution is it is extremely difficult writing any test case. So what would be a perfect solution. -
MainList is missing a QuerySet. Define MainList.model, MainList.queryset, or override MainList.get_queryset()
Hi there I am trying to have a homepage where I can list from a model called Lecturer and create forms from a model called DistributionForm. I tried it with the CreateView but I got the error MainList is missing a QuerySet. Define MainList.model, MainList.queryset, or override MainList.get_queryset(). in the that the queryset is missing. Can you please help me. Views.py class MainList(generic.CreateView): template_name='home.html' form=DistributionForm models=Lecturer fields=['distribution','semester','lecture','lecturer'] success_url = "/home" def form_valid(self,form): form.instance.author=self.request.user return super().form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context ['lecturer_list'] = Lecturer.objects.order_by('lecturer') return context urls.py from django.urls import path from . import views from django.conf.urls.static import static from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns app_name='distribution' urlpatterns=[ path('home/',views.MainList.as_view(),name='home'), path('hocalar/<slug:slug>/',views.LecturerDistribution.as_view(),name='lecturer_distribution'), path('dersler/<slug:slug>/',views.LectureDistribution.as_view(),name='lecture_distribution'), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and my home.html {% extends "base.html" %} {%block content%} {% load crispy_forms_tags %} <div class="container"> <div class="form-group pull-right"> <input type="text" class="search form-control" placeholder="Ara"> </div> <span class="counter pull-right"></span> <table class="table table-hover results"> <thead> <tr> <th >Hoca</th> <th >Ders</th> </tr> <tr class="warning no-result"> <td><i class="fa fa-warning"></i> Sonuç Yok</td> </tr> </thead> <tbody> {%for lec in lecturer_list%} <tr> <td> <p ><a style="text-decoration:none" href="{% url 'distribution:lecturer_distribution' slug=lec.slug%}">{{lec.lecturer}}</a></p> </td> <td> {%for ders in lec.lecture.all%} <a style="text-decoration:none" href="{% url 'distribution:lecture_distribution' slug=ders.slug%}">{{ders.lecture}}</a>, {% endfor%} </td> </tr> {%endfor%} … -
Django #hashtags in url
Sooo what am trying to do is a link on CONTACT to redirect to HOME and scroll down to some content, but dont know how to pass # in urls in django. Any help appreciated. The scroll is fine on home but cant get it to work from contact. URL path('/#products', HomeView.as_view(), name='products'), CONTACT.html <a class="nav-link" href="{% url 'core:products' %}">Produkty</a> HOME.html this is in navbar <a class="nav-link" style="cursor: pointer" onclick="window.location.href='#products'">Products</a> this is where i want it scrolled <a class="anchor" id="products"></a> -
Python-social-auth cannot refresh token
I use social-app-django(Spotify) and recently this piece of code started throwing an error: strategy = load_strategy() social.refresh_token(strategy) Gives error: requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://accounts.spotify.com/api/token How to fix? -
Checking in views whether the object passed in context exists or not
I am working on a basic django website . I am having a cart view as following: def cart(request): customer=request.user.customer order, created=Order.objects.get_or_create(customer=customer, complete=False) items=order.orderitem_set.all() context={ 'items':items, 'order':order, 'types' : Category.objects.all(), } return render(request,"cart.html",context) The items is the products that the customer has in his cart. I want to perform a check whether if the cart is empty(that is there are no items) then I can show a message that cart is empty and then can redirect to a certain page . I am trying to find a way to perform this check and show a message that cart is empty. Any help would be appreciated. Thanks. -
DJANGO DOC error:in was_published_recently, return self.pub_date >= (timezone.now() - datetime.timedelta(days=1)).timestamp()
in was_published_recently return self.pub_date >= (timezone.now() - datetime.timedelta(days=1)).timestamp() TypeError: '>=' not supported between instances of 'datetime.datetime' and 'float' def was_published_recently(self): return self.pub_date >= (timezone.now() - datetime.timedelta(days=1)) it showing warning in self.pub_date as "Expected type 'timedelta', got 'DateTimeField' instead" message and then i google it then https://code.djangoproject.com/ticket/30345#no1 I changed as def was_published_recently(self): return self.pub_date >= (timezone.now() - datetime.timedelta(days=1)).timestamp() after following documentation return self.pub_date >= (timezone.now() - datetime.timedelta(days=1)).timestamp() I got error as, TypeError: '>=' not supported between instances of 'datetime.datetime' and 'float' -
Test a logger value in a function in Django
How can I test a logger value in a function? views.py def foo(a): if a == b: return a + b else: logger.error('unable to process') test.py: class TestFoo(TestCase): # setup def test_correct_input(self): # do something def test_incorrect_input(self): # test that the logger returns a certain string -
Django DataError at /admin/posts/post/add/ integer out of range
I'm getting an integer out of range error when I create a new post in Django Admin. This is DRF project with a Post model that uses a UUIDField as id which is the primary key. It seems like the ID field is causing the problem but I don't understand how the UUIDField can be out of bounds. None of the remaining fields like Title or URL could be out of range. When I go to create a new post in the Admin dashboard, I get this error message after I click the Save button: DataError at /admin/posts/post/add/ integer out of range Request Method: POST Request URL: http://localhost:8000/admin/posts/post/add/ Django Version: 3.0.7 Exception Type: DataError Exception Value: integer out of range Exception Location: /Users/username/Desktop/Workspace/project-api/venv/lib/python3.7/site-packages/django/db/backends/utils.py in _execute, line 86 Python Executable: /Users/username/Desktop/Workspace/project-api/venv/bin/python Python Version: 3.7.3 Here's the Model: class UUIDModel(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) class Meta: abstract = True class TimeStampedUUIDModel(UUIDModel): created_at = models.DateTimeField(auto_now_add=True, editable=False) modified_at = models.DateTimeField(auto_now=True, editable=False) class Meta: abstract = True class Post(TimeStampedUUIDModel): creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") title = models.CharField( _("Title"), max_length=255, blank=False, null=False) description = models.TextField( _("Description"), max_length=1500, blank=False, null=False) url = models.URLField(_("URL"), unique=True, max_length=155, blank=False, null=False) country = models.CharField( _("Country"), max_length=120, blank=False, null=False) post_image = … -
The data in the 2nd plot in vertically stacked Plotly sub-plot not being displayed correctly in Django 3.1 app
I am running a Django 3.1 app using plotly to display an interactive chart in a .html template file. I am trying to create a plot using the subplots functionality. The plot has 2 rows and 1 column. The first row correctly displays the first chart which is a Candlestick plot of daily stock prices. The second row of the plot was to be a bar chart of the volume for each of the days of the stock price. When I run the app, I receive no server errors and the .html page loads as expected. However, the second plot should be a bar chart of the volume but the chart is blank. The plot correctly displays the yaxis and xaxis title and values for the tick as expected for the Volume data. If I set the axis_rangeslider_visible to True, then the chart displays the rangeselector in the 2nd chart where the volume data should be. The axis labels still display the expected values and labels as if the volume data is plotted. The following code is from my views.py file within the Django app. from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ListView, DetailView, CreateView, … -
Django - Upload image with POST request
I want to make user upload an image to my server via custom app. How to do I accomplish? I cannot use any kind of websites for uploading image. -
How to import postgreSQL Database to AWS?
I'm developing Django application and created PostgreSQL database in the local PC. After deploying the app to AWS, I wonder what is the best way to import PostgreSQL database to AWS which already created in the local PC. -
Converting embedded images to img
I'm working backend with a wagtail headless CMS and the frontend is JavaScript. I'm using a RichTextField and on the API it shows the image like this: "<embed alt="a" embedtype="image" format="fullwidth" id="3"/>" so because its embedtype it can't be shown on our page. I need to change the type to img with a src. I haven't tried anything because i don't even know how to start. This is the model with the RichTextField class ValueTagMotivation(Orderable, ClusterableModel): """Teams motivate why a tag was picked""" team = ParentalKey( TeamPage, on_delete=models.CASCADE, related_name="value_tag_motivations" ) value_tag = models.ForeignKey(ValueTag, on_delete=models.CASCADE, related_name="+") tagline = models.CharField(max_length=255) motivation = RichTextField( features=["bold", "italic", "ol", "ul", "link", "image", "embed"] ) panels = [FieldPanel("value_tag"), FieldPanel("tagline"), FieldPanel("motivation")] class Meta: # a team can only pick each tag once unique_together = (("team", "value_tag"),) -
Facebook Login (python social auth) - Trying to login throws page not found error
I have implemented social login using python-social-auth and was working fine, but suddenly notice the Facebook login throws Page not found error The url thats being called after the username and password screen is https://www.facebook.com/connect/uiserver.php?app_id=XXXXXXXXXXXXXXXX&next=https%3A%2F%2Fwww.facebook.com%2Fv3.2%2Fdialog%2Foauth%3F which says This page isn't available The link you followed may be broken, or the page may have been removed. I tried changing the app and still this persists -
Is there any way to link existing inputs to django form?
Working on an app, I initially started developing the UI via QT (PySide2) but I paused it to work on a full "online version" via Django. The fact is that I'm learning/discovering the framework and how it works step after step. For all HTML I'm building those on Bootstrap Studio which help me to save A LOT of time and of course make things totally easier for me. My current problem is that I just discovered how not simply inputs/forms works in Django (My own opinion !). My app works with several bootstrap modals in order to Add/Edit "element" which are the kind of instances of my app and which will be write/read/edit in database. The problem here is I already created all HTML pages and related modals and I can't find any way on the internet to link my existing modals to Django forms. As far as I understood Django forms "caricaturaly" works like this : Django generate a form that you have to dynamically integrate to your HTML. The fact is it doesn't really arrange me because : I already have my modals with their inputs looking how I want I don't really want a bad looking forms … -
How to stop Folder name to Store in Databse in Django?
I am uploading Image in my specific folder, but it's storing in my database table also, Please let me know how I can stop folder name to store in database. Currently my image is storing in my database table in this format thumb/20/08/18/image.jpeg, i don't want this thumb/20/08/18 to store in my database table, because it's my folder name with year, date and month. Here is my models.py file.. class Product(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) thumb_image= models.ImageField(upload_to='thumb/%y/%m/%d/', default=None) def __str__(self): return self.name -
Django-allauth for admin authentication using staff_member_required decorator: ERR_TOO_MANY_REDIRECTS for non-staff users
I am using django-allauth for the authentication workflow to my django admin site. The relevant snippet in my project-level urls.py file: from django.contrib import admin from django.contrib.admin.views.decorators import staff_member_required admin.site.log = staff_member_required(admin.site.login, login_url = 'accounts/login') admin.autodiscover() ... However, if a registered user, who is not a staff member logs in, the result is an ERR_TOO_MANY_REDIRECTS error. Ideally I would like to redirect the user to an 'access denied'-page. I looked at the documentation for the staff_member_required decorator, but I did not find a solution for how to redirect a user if the user is not a staff member but still registered. Does anyone have an idea? -
How to access Django form field for validation
I want to make validation methods on my Django form. by this I can validating easily through the Form instance class SignupForm(forms.Form): username = forms.CharField(label='username', max_length=255) password1 = forms.CharField(label='password', max_length=255, widget=forms.PasswordInput()) password2 = forms.CharField(label='retype password', max_length=255, widget=forms.PasswordInput()) def validate_password(self): if self.password1 == self.password2: return True else: return False def save(self): Account.objects.create( username=self.username, password=self.password1 ) print('${self.username} has been added!') by that I can use the form on my view like this post = request.POST form = SignupForm() if Account.objects.filter(username=post['username']).count() > 0: messages.warning(request, "account with the same username is already exists!") print("account saved") else: if form.validate_password(): form.save() messages.success(request, "Account has been added") else: messages.warning(request, "passwords don't match! {} {}".format(post["password1"], post["password2"])) return redirect("signup") I got an error in CLI like this AttributeError: 'SignupForm' object has no attribute 'password1' [18/Aug/2020 16:10:10] "POST /accounts/signup HTTP/1.1" 500 74586 I think it refers the if self.password1 == self.password2: line My error on my django response django error site But it seems like I got an error that the form doesn't have the attribute that I have assigned when creating the model. is there a way I can access the object instance's attribute in the form method? This is my first python project so I have not mastered … -
Django/VueJs app deployed to Heroku showing Application Error on Page
I have a django app with vuejs frontend to deploy to heroku. The build was successful and app was deployed. However, visiting the page of the site mysite.heroku.com shows an application error like so: 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. You can do this from the Heroku CLI with the command heroku logs --tail heroku logs --tail shows the follow error trace $ heroku logs --tail 2020-08-18T08:49:33.000000+00:00 app[api]: Build succeeded 2020-08-18T08:49:37.262466+00:00 heroku[web.1]: Starting process with command `gunicorn mysite.wsgi --log-file -` 2020-08-18T08:49:39.662296+00:00 app[web.1]: [2020-08-18 08:49:39 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-08-18T08:49:39.666320+00:00 app[web.1]: [2020-08-18 08:49:39 +0000] [4] [INFO] Listening at: http://0.0.0.0:24767 (4) 2020-08-18T08:49:39.666526+00:00 app[web.1]: [2020-08-18 08:49:39 +0000] [4] [INFO] Using worker: sync 2020-08-18T08:49:39.677004+00:00 app[web.1]: [2020-08-18 08:49:39 +0000] [10] [INFO] Booting worker with pid: 10 2020-08-18T08:49:39.712865+00:00 app[web.1]: [2020-08-18 08:49:39 +0000] [11] [INFO] Booting worker with pid: 11 2020-08-18T08:49:40.416283+00:00 heroku[web.1]: State changed from starting to up 2020-08-18T08:49:41.243989+00:00 app[web.1]: [2020-08-18 08:49:41 +0000] [10] [ERROR] Exception in worker process 2020-08-18T08:49:41.244036+00:00 app[web.1]: Traceback (most recent call last): 2020-08-18T08:49:41.244038+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-08-18T08:49:41.244039+00:00 app[web.1]: worker.init_process() 2020-08-18T08:49:41.244040+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 119, in init_process … -
POST Request works on POSTMAN but fails on my React
Hello so I have a Django API whereby I have the following in my DB: lecturer module video date So when I make a POST request to create another entry to my DB with POSTMAN everything works just fine leaving me to believe that my API is definitely handling everything properly. So now when I try to make a POST request on my client-side when I submit the data I get the following error: [*] Error: {'video': [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]} So I honestly do not know where I could be going wrong with how I am handling this request can I please get assistance with regards to this matter. Code below: ReactJS code how I tried to handle this POST request class VideoUploadForm extends Component{ constructor(props){ super(props); this.state = { lecturer: '', module: '', video: null, date: '' } this.handleChange = this.handleChange.bind(this); this.uploadVideo = this.uploadVideo.bind(this); } handleChange = (e) =>{ this.setState({ [e.target.id] : e.target.value }); } uploadVideo = (e) => { e.preventDefault(); let form_data = new FormData(); form_data.append('lecturer', this.state.lecturer); form_data.append('module', this.state.module); form_data.append('video', this.state.video); form_data.append('date', this.state.date); let url = 'http://127.0.0.1:8000/api/upload-lecture/'; axios.post(url, form_data, { headers: { 'Accept':'application/json', 'content-type': 'application/json' } … -
Django sql statements with non english symbols
I have sql statement, with non english symbols in where (sap_code variable contains russian text) sap_code = 'ОВОЩИ – ФРУКТЫ' sql_string = 'SELECT ' \ 'SAP_CODE, ' \ 'SKU, ' \ 'FROM INFO ' \ f'WHERE ROWNUM < {settings.NQ_SQL_LIMIT}' if sap_code: sql_string += f' AND SAP_CODE = {sap_code}' with connections[db].cursor() as cursor: exec_result = cursor.execute( sql_string ) And I get such error django.db.utils.DatabaseError: ORA-00911: invalid character (oracle database) Is there any way to fix that? -
Django's SECURE_SSL_REDIRECT and Heroku causes redirected Rest Framework POST requests to become GET requests
I have Django project hosted on Heroku There's a web-application and a Django REST API. I'm using SECURE_SSL_REDIRECT and SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') to redirect all http traffic to https. The web-application is happy. If I try to use a http link, it redirects to https, and I can use forms, etc. For the Django REST API, if I try a http link and a POST request, it redirects successfully to https but the method becomes a GET and the API requests the request (because it is meant to be a POST). I do not know if this is expected behaviour, or if this is a Heroku specific thing. If it's expected for redirects, I'd appreciate to understand why (from a technical point). And or if there is a solution. -
Max retries exceeded with url
Hello I have a problem with my Django code : I tried this : requests.post('https://localhost:8000/api/test/', data=data, headers={'Content-Type': 'application/json'}, verify=False) But I got this : {SSLError}HTTPSConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /api/test/ (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:852)'),)) I achieved to solve the problem using http instead of https but I want to use https. How can I do this knowing that all of this is on localhost ? Thank you very much ! -
This field is required.Django
i have a problem, my request.files is not working, it say this field is required. so its mean my files not appear, can you see my code and tell me what code is wrong? thanks this is my html <form enctype="multipart/form-data" class="user" method="POST"> {% csrf_token %} <div class="form-group"> <label for="exampleTextarea">Surat Pernyataan RT RW</label> <div class="col-sm-12"> <div class="input-group mb-3"> <div class="custom-file"> {{surat_form.file_surat_pernyataan}} </div> </div> </div> </div> </form> this is my form class Surat_Sktm(forms.ModelForm): class Meta: model = Pengajuan_SKTM fields = ['file_surat_pernyataan'] this is my models class Pengajuan_SKTM(models.Model): file_surat_pernyataan = models.FileField(upload_to='documents/%Y/%m/%d/') this is my views def get_document(request): if request.method == 'POST': surat_form = Surat_Sktm(request.POST, request.FILES) if surat_form.is_valid(): user = surat_form.save() user.save() context = {'surat_form': surat_form} filename = fill_template('surat_sktm.odt', context, output_format='pdf') visible_filename = 'surat-sktm.pdf' return FileResponse(filename, visible_filename) else: surat_form = Surat_Sktm() return render(request, 'pengurusan/sktm.html', { 'surat_form': surat_form, }) else: surat_form = Surat_Sktm() return render(request, 'pengurusan/sktm.html', { 'surat_form': surat_form, })