Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding a field to queryset in django
I have a model whose fields are datetimefields start_time and end_time I want to display on the API- start_time, end_time and the difference between them However, I don't want to use for or while loop to achieve this because it is too slow How can I get the difference on the API without looping -
Convert Datetime.Date to DT Format Int
Im trying to convert the following datetime.date field into a dt format off my django form to send to Microsoft API. Here is my code. form = NewEventRequestViewForm(instance = record_id) obj = form.save(commit= False) print(obj.date) 2020-5-12 new_event.start = dt.datetime(obj.date) <--- this created an error because its not in int form. How do I convert this so this is the format new_event.start = dt.datetime(2020, 5 , 12) Thanks for the help! -
Django3.0 : GDALException while accessing model form
I am trying to save shops with the geo locations in Django project. And I am able to save the data from admin UI but getting exception when I access the saved data. In my django app (shop) I have following models.py from django.contrib.gis.db import models class Shop(models.Model): name = models.CharField(max_length=100) location = models.PointField() address = models.CharField(max_length=100) city = models.CharField(max_length=50) I have installed django-leaflet settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'leaflet', 'shops' ] admin.py looks like this #from django.contrib import admin from django.contrib.gis import admin from .models import Shop from leaflet.admin import LeafletGeoAdmin class ShopAdmin(LeafletGeoAdmin): list_display = ('name', 'location') admin.site.register(Shop, ShopAdmin) From admin UI I am able to create shop but when I try to open any shop to view saved data I see following exception Environment: Request Method: GET Request URL: http://localhost:8000/admin/shops/shop/16/change/ Django Version: 3.0.6 Python Version: 3.7.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'leaflet', 'shops'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template F:\workspaces\Django\env\lib\site-packages\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 19 OGR failure. 9 : {% for field in line %} 10 : <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if … -
How to link two model classes in django so that if the input of a user matches a part of the other model class, it retrieves those instances?
I have a project where a user can enter their credentials: user, datasource username, data source, and a new password. When they press submit, it updates the objects that have the same user, datasource username, and data source as what the user submitted and updates those passwords with the new password. These objects are called PcolCredentials objects since they have credentials such as the ones listed above, and these creds have their own model classes. The whole premise of the project works, but the only problem is that it only works with a PcolDataSource. There are two model classes, Pcoldatasource and Datasource, and I am supposed to have a user enter their DataSource in the form, not a Pcoldatasource. In the backend, these objects have PcolDataSources so obviously the form requires a PcolDataSource. I need to use a DataSource instead, and when the user enters a DataSource, it will update all passwords of every object that has that DataSource in a PcolDataSource. For example, a user enters "Dev" as a DataSource and the PcolDataSource of objects that have Dev are Prod, Dev, Test. This will update the password all objects that have Dev in the PcolDataSource Prod, Dev, Test. I … -
sending json in formdata to Django
I am trying to send the field documentregulation_set as json within formData, with some other fields, to my Django backend. This is what is looks like in the outgoing request: documentregulation_set: [{"regulation":2,"value":2,"label":"Regulation 1"},{"regulation":4,"value":4,"label":"Regulation 2"}] name: test file: (binary) My view looks like this: class DocumentView(generics.ListCreateAPIView): def create(self, request): pprint(request.data) and when the data is printed, however, it looks like: { 'documentregulation_set': '[{"regulation":2,"value":2,"label":"Regulation 1"'},{"regulation":4,"value":4,"label":"23NYCRR500"}]', 'file': <InMemoryUploadedFile: Flank Operational.docx (application/vnd.openxmlformats-officedocument.wordprocessingml.document)>, 'name': 'test', } Which is of course not json. Django seems to be interpreting the json as a string. How do I go about sending form data as json in this situation? -
Why we use get user model in the forms
Hello guys I want to ask that why we use get user model, can anyone please explain me what is the purpose of it. from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm class UserCreateForm(UserCreationForm): class Meta(): model = get_user_model() fields = ('username', 'email', 'password1', 'password2') -
django-rest-auth: Error: DoesNotExist: EmailAddress matching query does not exist
I am trying to use django-rest-auth inside of my django project. I have been able to sucessfully implemented it into my project. I can sign up and login. But I wanted a feature to add users from admin app. So I wrote a custom form to add new users. But after creating the user....I cannot login with the provided credentials. I get the following error, when I try to login: Traceback (most recent call last): File "/Users/goutambseervi/PycharmProjects/ventinghub-backend/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/goutambseervi/PycharmProjects/ventinghub-backend/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/goutambseervi/PycharmProjects/ventinghub-backend/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/goutambseervi/PycharmProjects/ventinghub-backend/venv/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/goutambseervi/PycharmProjects/ventinghub-backend/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Users/goutambseervi/PycharmProjects/ventinghub-backend/venv/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/goutambseervi/PycharmProjects/ventinghub-backend/venv/lib/python3.7/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/Users/goutambseervi/PycharmProjects/ventinghub-backend/venv/lib/python3.7/site-packages/dj_rest_auth/views.py", line 46, in dispatch return super(LoginView, self).dispatch(*args, **kwargs) File "/Users/goutambseervi/PycharmProjects/ventinghub-backend/venv/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/Users/goutambseervi/PycharmProjects/ventinghub-backend/venv/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/Users/goutambseervi/PycharmProjects/ventinghub-backend/venv/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/Users/goutambseervi/PycharmProjects/ventinghub-backend/venv/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/Users/goutambseervi/PycharmProjects/ventinghub-backend/venv/lib/python3.7/site-packages/dj_rest_auth/views.py", line 104, in post self.serializer.is_valid(raise_exception=True) File "/Users/goutambseervi/PycharmProjects/ventinghub-backend/venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 234, in … -
python no such table: weather_city
I getting these error . I have done migration migrate several time but still getting these error models.py class City(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Meta: verbose_name_plural = 'cities' views.py def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=271d1234d3f497eed5b1d80a07b3fcd1' city = "Boisar" r = requests.get(url.format(city)).json() city_weather = { 'city': city, 'temperature': r['main']['temp'], 'description': r['weather'][0]['description'], 'icon': r['weather'][0]['icon'], } context = {'city_weather': city_weather} return render(request, 'weather/weather.html', context) These is my model and view please figure out my error. Thanks -
Test in Django, reverse with no arguments not found
I want to test two views in Django: class TestSubstitute(TestCase): def test_Substitute(self): url = reverse('finder:substitute') url_with_param = "{}/{}/".format(url, 1) self.response = self.client.post(url_with_param) self.assertEqual(self.response.status_code, 200) class TestDetails(TestCase): def test_Details(self): url = reverse('finder:detail') url_with_param = "{}/{}".format(url, 1) self.response = self.client.post(url_with_param) self.assertEqual(self.response.status_code, 200) But whenever I ran those tests, I get: django.urls.exceptions.NoReverseMatch: Reverse for 'detail' with no arguments not found. 1 pattern(s) tried: ['finder/(?P<product_id>[0-9]+)/$'] django.urls.exceptions.NoReverseMatch: Reverse for 'substitute' with no arguments not found. 1 pattern(s) tried: ['finder/substitute/(?P<product_id>[0-9]+)/$'] My URLS: app_name = 'finder' path('<int:product_id>/', views.detail, name='detail'), path('substitute/<int:product_id>/', views.substitute, name='substitute'), I've tried to pass '1' and 1 to my url but with no luck. I've made a setup with temporary products with their id. -
Django: In one model I have used User model as foreign key, I want to autofill the username while creating my Model
class ReplyPost(models.Model): topic = models.ForeignKey(CreatePost, blank=True,null=True, related_name='subject_post', on_delete=models.CASCADE) #message = models.TextField(validators=[validate_post_word_count]) message = models.TextField() create_reply_date = models.DateTimeField(auto_now_add=True) update_reply_date = models.DateTimeField(auto_now=True) reply_by = models.ForeignKey(User, blank=True, null=True, related_name='replier_post', on_delete=models.CASCADE) I have this model, On creating replyPost I want to fill reply_by with current user I tried: form.cleaned_data['created_by'] = request.username After saving the form it didn't save username. In had printed the form it show this field as tag .. How can fill this as selected in Django form -
How to overwrite data in a model if it has the same date in Django?
I'm trying to make model that saves logs from the user. I'm trying to implement a feature that overwrites the log if the same date exists. How can I get started with that? I just need some hint on what to do. Thanks in Advance and any help is aprreciated. Here is my views.py: @login_required def dprmodelform(request): if request.method=='POST': form = dprform(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.testuser = request.user messages.success(request, 'Success! Your DPR log has been saved!') instance.save() else: messages.error(request, 'Oh no! Your DPR log has an error!') form = dprform() return render (request,'users/dprform.html',{'form':form}) -
Python/Django concise logging of `get_or_create`
What would be the concise way to log if an object was created? get_or_create returns obj, created: bool Doing something like: myobj, created = get_or_create(...) if created: logger.info("Object %s created", obj) else: logger.info("Object %s fetched", obj) The Aproach above is: very wordy (especially if it gets repeated for many objects) has bad performance (on each object creation an if statement) Putting this logic into a separate function also seems bad (would mean using some custom function instead of standartized log function) What would be the concise aproach here? -
Forbidden (CSRF cookie not set.) in Django jQuery POST
I have a Django 3 application with jQuery Ajax posts on bootstrap modals. There are few buttons that do not have any form but uses post to call certain urls. All the Django methods are implemented as stated here: https://docs.djangoproject.com/en/3.0/ref/csrf/ All the headers are sent properly. The page and and functionality works fine when user has logged in and also after user has logged out. However the Ajax calls return the error response as Forbidden (CSRF cookie not set.), when visiting the site first time and in Incognito mode when not logged in. Once user logs in the issue gets resolved, even after the user logs out. Please guide as to what may be the probable reason. -
How fix error for django dumpdata "_django_curs_139705..."
Try dumpdata for my projest python3 manage.py dumpdata > dump_12_05_2020.json Get error. How i can fix that? CommandError: Unable to serialize database: cursor "_django_curs_139705045542656_66" does not exist -
Django filter() by ForeignKey returns incorrect queryset
I have two models, Product model connects to ProductGroup by ForeignKey and a Product model also has a ForeignKey field named shop: class ProductGroup(models.Model): name = models.CharField(max_length=64) vat_rate = models.ForeignKey(VatRate, verbose_name="VAT in percent", related_name='product_group_vat_rates', on_delete=models.CASCADE) class Product(models.Model): product_id = models.CharField(max_length=128, blank=True, null=True) name = models.CharField(max_length=128) shop = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name="product_shop") product_group = models.ForeignKey(ProductGroup, on_delete=models.CASCADE, related_name="product") price = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True, default=0) cost_price = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True, default=0) stock_amount = models.IntegerField(default=0, blank=True, null=True, help_text=_('Product amount in stock')) barcode = models.CharField(max_length=64, blank=True) is_active = models.BooleanField(default=True) Let's assume, I have two Product instances, connected to particular shop, and one ProductGroup, that connected to this two Product instances So now I want to get all ProductGroup instances, that relate to particular shop instance. What I do: product_group_list = ProductGroup.objects.filter(product__shop=shop_inst) What I think I will get: <QuerySet [<ProductGroup: Product Group test product group>]> But, unfortunately, I get this: <QuerySet [<ProductGroup: Product Group test product group>, <ProductGroup: Product Group test product group>]> So it returns to me queryset of these two ProductGroup instances connected to Product instances. How can I improve my query to DB to get only ONE ProductGroup instance, that connected to this shop? (Because there's only one record in DB with … -
How do I limit characters using JQuery in Django?
I want to limit users to only placing five characters for the zip code. Here's what I have so far (that doesn't seem to work). What I'm going for is if someone accidentally submits more than five characters, then the script will delete off all but the five most recent characters. Is this the best route? sign-up.html <script> var max_chars = 5; $('#zip_length').keydown( function(e){ if ($(this).val().length >= max_chars) { $(this).val($(this).val().substr(0, max_chars)); } }); $('#zip_length').keyup( function(e){ if ($(this).val().length >= max_chars) { $(this).val($(this).val().substr(0, max_chars)); } }); </script> ... <form action="" method="POST" class="mt-4" enctype="multipart/form-data"> {% csrf_token %} {% crispy form %} </form> ... forms.py ... zip = forms.CharField(label='Zip', required=True, widget=forms.TextInput(attrs={'placeholder': 'Enter your zip', 'id': 'zip_length'})) ... def __init__(self, *args, **kwargs): super(ProfileUpdateForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( ... Row( Column('city', css_class='form-group col-4'), Column('state', css_class='form-group col-4'), Column('zip', css_class='form-group col-4') ), ... ) -
Why is Index Error arising(tuple index out of range)?
Actually,I am working on a Django project which uses sql.Whenever I try to go to a particular link on the site.The referenced page does not open and it shows tuple index out of range.The error is sbowing on line 23 of the code.I can't understand the reason behind it.The indices seem to be okay. def form_valid(self, form): key_word = form.cleaned_data['search'] key_word = '%' + key_word + '%' context = {} if self.request.user.is_authenticated: with connection.cursor() as cursor: cursor.execute('SELECT * ' + 'FROM `author` ' + 'WHERE `id` = %s;', [self.request.user.author_id, ]) row = cursor.fetchone() context['username'] = row[1] with connection.cursor() as cursor: sql = """SELECT `publication`.`id`, `title`, `description`, `date`, `location`, `publisher`.`id`, `publisher`.`name`, `publisher`.`type` FROM `publication`, `publisher` WHERE `approved`=TRUE AND (`title` LIKE %s OR `description` LIKE %s);""" cursor.execute(sql, [key_word, key_word]) tbl = cursor.fetchall() if tbl is not None and tbl[0] is not None: context['publications'] = [] for row in tbl: get_publication(row, context) return render(self.request, 'portal/search.html', context) -
convert DateTimeField to datetime
I have a django.db.models.DateTimeField defined here: expiration = models.DateTimeField(name="expiration") and I want to compare it to datetime like this: return self.expiration > datetime.datetime.now() but the pycharm gives me the following warning: Expected type 'datetime', got 'DateTimeField' instead How can I convert django.db.models.DateTimeField to datetime to solve this problem? -
Customizing (style) ModelMultipleChoiceField in a on ManyToManyFields in Django
Am trying to customize my checkbox inputs to look like this [what i want to archive] so i tried this... profile.html <ul class="wt-accountinfo"> {% for key, value in form.interests.field.choices %} <li> <div class="wt-on-off pull-right"> <input type="checkbox" id="{{ value }}" value="{{ key }}" name="interests"> <label for="{{ value }}"><i></i></label> </div> <span>{{ value | title }}</span> </li> {% endfor %} </ul> which renders the html fine but highlight the select fields from the database but using {{ form.interest }} highlights the selected checked boxes from the database here is the forms.py class ProfileForm(forms.ModelForm): interests = forms.ModelMultipleChoiceField( queryset=JobsCategories.objects.all(), widget=forms.CheckboxSelectMultiple(), required=False ) class Meta: model = Profile fields = ['interests'] and here is the models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, interests = models.ManyToManyField(Categories, related_name='interests', null=True, blank=True) def __str__(self): return f'{self.user.first_name} {self.user.last_name}' in the views.py def dashboard_profile(request): if request.method == 'POST': form = ProfileForm(request.POST, request.FILES, instance=request.user.profile) account_form = AccountForm(request.POST, instance=request.user) if form.is_valid() and account_form.is_valid(): f_interests = form.save(commit=False) for i in request.POST.getlist('interest'): f_interests.interest.update(i) f_interests.save() form.save_m2m() account_form.save() return redirect('index') else: form = ProfileForm(instance=request.user.profile) account_form = AccountForm(instance=request.user) context = { 'form': form, 'account_form': account_form, } return render(request, 'dashboard_profile.html', context) NOTE!!! if i select the options i want and click save, it saves the options i checked to the … -
'str' object has no attribute 'user' error in Django
I have a view in Django and I have to call another function in this view. When i call the function in the view, the i got 'str' object has no attribute 'user' error. But when i delete the function call, there is no error. It gave the error in django contrib decorator such as below. C:\Users\imgea\Anaconda3\lib\site-packages\django\contrib\auth\decorators.py in _wrapped_view redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. """ def decorator(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = request.build_absolute_uri() resolved_login_url = resolve_url(login_url or settings.LOGIN_URL) # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urlparse(resolved_login_url)[:2] My view; def optimize(request): customer_name = str(request.user) model_name = customer_name + "_cost" nominals = ['material_type','program','isleme_merkezi', 'baglama_sekil', 'ymmm', 'tezgah_kodu'] cost_id = request.session['opt_id'] optimization_features = request.session['opt_features'] cost = Cost.objects.get(id=cost_id) cost_dict = model_to_dict(cost) features = request.user.profile.selected_features unknown_nominal_column_names = [] unknown_column_names = [] unknown_initial_guess = [] known_map = dict() for feature in features: known_map[feature] = cost_dict[feature] for feature in optimization_features: if feature in nominals: unknown_nominal_column_names.append(feature) else: unknown_column_names.append(feature) unknown_initial_guess.append(float(known_map[feature])) values, optimize_cost = optimize_parameters(customer_name, … -
How to fetch JSON data using AJAX request in Django using default login?
I want to display a text on the webpage whenever user presses a button. The packet should be fetched using AJAX request from a Django server which usage the Django's default login system. -
CSRF Token on JS Fetch Django
I make a post request like this from a django template: fetch("http://127.0.0.1:8000/post_request", { method: "POST", body: JSON.stringify(context), }).then(function(data) { print(data) }); Then, I get this error: Forbidden (CSRF token missing or incorrect.): /post_request I think it is because I dont add the {% csrf_token %} tag, but don't know how to do this with a fetch api post request. Anyone know? Thanks! -
Django Creating Item Defaults when being Created Model not working
Hi I am trying to set a default variation for each item created to be Small medium and large I am getting 'str' object has no attribute 'all' I tried fixing it but other errors show up, what is the best way if this code is not correct to create 3 sizes default for every item created I don't have a category class just an option which I think might be causing the problem Here is the model: class Item(models.Model): title = models.CharField(max_length=100) price = models.DecimalField(decimal_places=2, max_digits=100) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField(unique=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) update_defaults = models.BooleanField(default=False) def __str__(self): return self.title class Meta: unique_together = ('title', 'slug') class VariationManager(models.Manager): def all(self): return super(VariationManager, self).filter(active=True) def sizes(self): return self.all().filter(category='size') def colors(self): return self.all().filter(category='color') VAR_CATEGORIES = ( ('size', 'size',), ('color', 'color',), ('package', 'package'), ) class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) category = models.CharField( max_length=120, choices=VAR_CATEGORIES, default='size') title = models.CharField(max_length=120) image = models.ImageField(null=True, blank=True) price = models.DecimalField( decimal_places=2, max_digits=100, null=True, blank=True) objects = VariationManager() updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) def __str__(self): return self.title def item_defaults(sender, instance, created, *args, **kwargs): if instance.update_defaults: categories = instance.category.all() for cat … -
Calling a data from a csv file and show into a html page using django
I am working on a project where I need to import data from a csv file and show an element (suppose the first element, that is first row first column). I am importing the data via a form.py file. There the code is: import pandas as pd from django.shortcuts import render def allblogs(request): input_file = pd.read_csv('file.csv', header= None) return render(request, 'blog/allblogs.html', {'name': input_file[0][0], 'age': input_file[0][1], 'job':input_file[0][2]}) The html page can be just: {{name}} But I am seeing nothing (no error as well) in the html output. Can anyone help? -
Django find only out referer
I use these code and its working, request.session['ref'] = request.META.get('HTTP_REFERER', 'Direct') After this code I capture referer and save it in sessions. but this code save in session just previous url. I just want save from outside referer, etc. from google, facebook, twitter I do not want it to save referer sessions in my website url's. like :: mysite/previous_page How can i solve this? Any idea?