Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, }) -
Allowing multiple options in username field in django login
I am working on a django website. I have a custom user model as follows: class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) mobile = models.CharField(max_length=12) first_name=models.CharField(max_length=20) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['mobile','first_name'] I am wanting to also add mobile to the username field so that a user can login using both email and mobile . I looked up to django docs but wasnt able to figure out a solution that would have worked for me. Please tell me a way so that I can proceed with it. -
In django 2.2. select_related field is not working? How to Fix it
I tried to join two tables in Django orm one is sample 1 and another one is sample 2 table. I used select_related functionality. but It's throwing an error on how to fix it. Models.py class Sample1( models.Model ) a = models.Charfield(max_length=10) b = models.Charfield(max_length=20) sample3 = models.ForeignKey(Sample3, null=True, blank=True, on_delete=models.SET_NULL) sample4 = models.ForeignKey(Sample4, null=True, blank=True, on_delete=models.SET_NULL) class Sample2( modes.Model ) sample1= models.ForeignKey( Sample1,on_delete=models.CASCADE ) created = models.DateTimeField() updated = models.DateTimeField() Views.py def sample_data(request): sampl_data = Sample1.objects.select_related("sample2__sample1").filter( created__lte = '2018-11-01 00:00:00-05:00', updated__gte = '2013-10-31 00:00:00-05:00') print(samp1_data) When I tried to run this program It's show this error django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'sample2'. Choices are: sample3, sample4 -
Django adding data to a database table with foreign key
I have a model with a foreign key to standard Django User database. models.py class Links(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) full_link = models.CharField('Полные ссылки пользователя', max_length=100) short_link = models.CharField('Короткие ссылки пользователя', max_length=100) class Meta: verbose_name = 'Ccылка' verbose_name_plural = 'Ссылки' def __str__(self): return self.full_link There is my forms.py and views.py forms.py class AddLink(forms.ModelForm): full_link = forms.CharField(required=True) short_link = forms.CharField(required=True) class Meta: model = Links fields = ['full_link', 'short_link'] views.py def link(request): if request.method == "POST": addUserLink = AddLink(request.POST) if addUserLink.is_valid(): addUserLink.user = request.user addUserLink.save() messages.success(request, f'Ссылка добавлена') else: addUserLink = AddLink() return render(request, 'users/links.html', {'userLinks': userLinks, 'title':'Пользовательские ссылки', 'addUserLink': addUserLink}) I want to add a record to the Link table in the database. An authorized user enters values in the form, and I have an error NOT NULL constraint failed: users_links.user_id. I think when I try to submit the form it does not send user_id. Why? -
How to post data to a locally hosted Django rest API
I am having trouble to understand the flow of data into a Django rest api. I found the following example: Django - Transforming Form data to REST API, POST request import requests def user_login(request): # If token was already acquired, redirect to home page if request.session.get('api_token', False): return HttpResponseRedirect(reverse('index')) # Get username and password from posted data, authenticate and # if successful save api token to session if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') r = requests.post('http://localhost/api-token-auth/', data={'username': username, 'password': password}) if r.status_code == 200: response = r.json() token = response['token'] # Save token to session request.session['api_token'] = token else: messages.error(request, 'Authenntication failed') return HttpResponseRedirect(reverse('login')) else: return render(request, 'login.html', {}) in the accepted answer of the stack question above I don't understand where this file would go, would it go in the views.py file ?. How is this function actually called ? Do I have to call it manually ? I also don't understand how to actually post data. once, again in the answer he shows to use requests . . . but could this be called from example from a jupyter notebook, or using the python command line ? r = requests.post('http://localhost/api-token-auth/', data={'username': username, 'password': password}) -
Django Formset Edit View
Iam working with a django formset. Some one please help me with edit view of this formset. Here is the create view. def create(request): context = {} InvoiceFormset = modelformset_factory(Invoice, form=InvoiceForm) form = OrderForm(request.POST or None) formset = InvoiceFormset(request.POST or None, queryset=Invoice.objects.none(), prefix='invoice') if request.method == "POST": if form.is_valid() and formset.is_valid(): try: with transaction.atomic(): order = form.save(commit=False) order.save() print("form saved") for invoice in formset: data = invoice.save(commit=False) print(data) data.invoice_id = order data.save() print("formset saved") except IntegrityError: print("Error Encountered") return redirect('/', messages.success(request, 'Order was successfully created.', 'alert-success')) context['formset'] = formset context['form'] = form return render(request, 'new.html', context) -
NoReverseMatch at / Reverse for 'movies-detail' with arguments '('Dark',)' not found. 1 pattern(s) tried: ['(?P<name>[^/]+)/(?P<id>[0-9]+)/$']
i want to pass the 2 url tags but get the error in that <h2><a class="article-title" href="{% url 'movies-detail' movie.name movie.id %}">{{ movie.name }} {{ movie.id }}</a></h2> want to receive that in the urls.py and show that path('<str:name>/<int:id>/',MoviesDetailListView.as_view(), name='movies-detail'),