Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a piece-by-piece decrease of an item from the cart
In template has a basket with arrows for adding and removing items. Adding made like this Template: <a href="{% url 'add' %}?new={{order.book.id}}" > Views def add(request): book = str(request.GET.get("new")) user = request.user order = Orders.objects.create(user = user, order_book = Book.objects.get(id=book)) order.save() return redirect("cart") And how to make a decrease by one element? This is how the cart view looks like: def cart(request): book_list = Orders.objects.filter(user = request.user) array = [b.order_book.id for b in book_list] array_price = sum([b.order_book.price for b in book_list]) result = {i: array.count(i) for i in array} ordered_list = [] for i in result: book = Book.objects.get(id = i) count = result[i] order = {'book': book, 'count':count, "price":book.price * count} ordered_list.append(order) """ Подсчет """ user = request.user order_list = Orders.objects.filter(user = user) count = len(order_list) context = {'ordered_list':ordered_list, "count":count, "price_total":price_total} return render(request, 'main/cart.html', context) Models.py: class Orders(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'users') order_book = models.ForeignKey(Book, on_delete=models.CASCADE) def __str__(self): return f'User {self.user} buy {self.order_book.title}' I tried to do this: def del_item(request): book = str(request.GET.get("new)) user = request.user del_book = Orders.objects.filter(user = user, order_book = Book.objects.get(id=book)) del_book.delete() return redirect("cart") But this removes all of the user's orders cleanly. It is also a useful function, but how can you do … -
Django ManyToMany intermediary through table & constraints for product watchlists
I want to implement multiple "watchlists" that each user can add products into. A basic reproduction of the tables I currently have is as follows: class Product(models.Model): name = models.CharField(blank=False, null=False, unique=True, default=None, max_length=100) sku = models.CharField(blank=False, null=False, unique=True, default=None, max_length=100, verbose_name='Stock Keeping Unit') description = models.TextField(blank=True) price = models.FloatField(blank=True) class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) display_name = models.CharField(max_length=30) subscription = models.CharField(null=False, blank=False, choices=SubscriptionChoices.choices, default=SubscriptionChoices.SILVER, max_length=100) watchlists = models.ManyToManyField(Product, through='Watchlist') class Watchlist(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) name = models.CharField(null=False, blank=False, max_length=20, default='WatchList1') As it can be seen above, I have chosen to use an intermediary 'through' table called Watchlist. I did so because I wanted to able to allow the user to rename the watchlist as they please, hence I included a field called name in the Watchlist table. I also have 3 levels of subscription that the user can have: Silver, Gold & Platinum. How do I do the following: Limit the number of watchlists to 2/5/10 depending on subscription level of user (2:Silver, 5: Gold etc). Limit the number of products in a watchlist to 10/20/30 again depending on subscription level of user. Add/remove products into a particular watchlist of a particular user. … -
Django Rest Framework: Serialize an Array in a multipart/form-data request
I am trying to send a List / array using multipart/form-data. The ModelSerializerdefines that field using class RequestSerializer(serializers.ModelSerializer): # ... in_categories = serializers.PrimaryKeyRelatedField(many=True, read_only=True) the Model field is defined as class Request(models.Model): # .... in_categories = models.ManyToManyField(to='Category', through='RequestToCategory', blank=False) now, I got a ModelViewSet defined as follows: class RequestViewSet(viewsets.ModelViewSet): # ... def create(self, request, *args, **kwargs): print(request.data) serializer = self.get_serializer(data=request.data) print(serializer.is_valid(raise_exception=True)) print(serializer.validated_data) However, the in_categories field never gets populated with actual data, nor does the validator raise an exception when called. I did not find any way to transmit the data in a way the field actually gets a list of keys as defined. I tried three things: Sending the data as literal resulting in request.data = <QueryDict: { ... 'in_categories': ['[2, 3]'] ... Sending the data as array resulting in request.data = <QueryDict: { ... 'in_categories[0]': ['2'], in_categories[1]': ['3'] ... Sending the data as array with extra key resulting in request.data = <QueryDict: { ... 'in_categories[0]id': ['2'], in_categories[1]id': ['3'] ... Each solution (i) arrives at the ViewSet, (ii) validates correctly but does (iii) not reflect into serializer.validated_data. Do I miss something? I spent already hours on this, finding no solution on how to make DRF understand what I want. -
admin Panel: TypeError: expected str, bytes or os.PathLike object, not list
I'm getting this error while trying to upload a picture in http://127.0.0.1:8000/admin/: TypeError: expected str, bytes or os.PathLike object, not list [23/Oct/2020 12:15:22] "POST /admin/store/category/4/change/ HTTP/1.1" 500 166634 I'm using MacOS 10.15.7 Python 3.9 Django 3.1.2 pandas 1.1.3 from django.db import models class Category(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) image = models.ImageField(upload_to='category', blank=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='product', blank=True) stock = models.IntegerField available = models.BooleanField(default=True) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) Do you have any idea how to solve it? Thanks -
Django multilanguage: language switcher does not respect prefix_default_language=False
I'm trying to implement a language switcher in a website with 2 languages. I use prefix_default_language=False in order to have English in the root domain without the subfolder /en/. The problem is that when I try to make a language switcher like it's explained in Django docs, it redirects me to /en/ which is also working. I just want en to be in the root without any subfolder as it is the default language. This is what I've done: Settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # Middleware for translations 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # Default language LANGUAGE_CODE = 'en-us' # Languages supported by translation LANGUAGES = [ ('en', ('English')), ('es', ('Spanish')), ] TIME_ZONE = 'UTC' # Enable translations USE_I18N = True USE_L10N = True USE_TZ = True # Directory for translations LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale') ] urls.py from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView from django.conf.urls.i18n import i18n_patterns from django.utils.translation import gettext_lazy as _ urlpatterns = [ # endpoint for the language switcher path('i18n/', include('django.conf.urls.i18n')), # Robots.txt file path('robots.txt', TemplateView.as_view(template_name="core/robots.txt", content_type='text/plain')), ] urlpatterns += i18n_patterns( path(_('admin/'), admin.site.urls), path('blog/', include('blog.urls')), path('', include('staticpages.urls')), # Hide language prefix in URLs for default language … -
Postgres optional array parameter in Django raw sql
So I've used this question to create optional parameters in my Django raw_sql snippet: select da.data_date, hll_union_agg(dau.users) users_union from sales_dailyaggregationusers dau join sales_dailyaggregation da ON da.id = dau.daily_aggregation_id where outlet_id in %(outlet_ids)s and currency = %(currency)s and (%(transaction_channels)s is NULL or transaction_channel in %(transaction_channels)s) and (%(transaction_types)s is NULL or transaction_types && %(transaction_types)s) However, Django gives the following error: django.db.utils.ProgrammingError: syntax error at or near "NULL" LINE 11: ... and (NULL is null or transaction_channel in NULL) So it looks like it's processing the entire query and deciding that it's badly formed (even though Postgres would optimize away the second half of the code). Is there a way around this? -
Django templates render newline as \n instead of <br>
I'm generating an XML file using Django template language and I came across a problem with linebreaks. I'm trying to render textarea but I need to keep newlines - \n because the facebook catalogue feed accepts only \n as a newline. I can't figure out how to make it work. linebreaks filter doesn't work. Also |safe doesn't seem to work. <description><![CDATA[{{ object.description|safe|truncatechars:5000 }}]]></description> Do you know how to do that? -
Why is Django Crispy Forms throwing "module 'django.forms.forms' has no attribute 'BoundField'"
When I use the "|crispy" or "|as_crispy_field" filters on my form/fields, I get an error that the field has no attribute BoundField. This was working fine, but I updated django/crispy forms, and I'm not sure whether I missed a trick? The form works fine without the filter. forms.py: from django import forms from django.utils import timezone from bootstrap_modal_forms.forms import BSModalForm from backgammon import models class MatchForm(BSModalForm): date_played = forms.DateField(initial=timezone.now) class Meta: model = models.Match fields = [ 'date_played', 'winner', 'score' ] views.py from django.contrib.auth.mixins import PermissionRequiredMixin from bootstrap_modal_forms.generic import BSModalCreateView from .forms import MatchForm class MatchCreate(PermissionRequiredMixin, BSModalCreateView): permission_required = 'backgammon.add_match' template_name = 'backgammon/match_form.html' form_class = MatchForm success_message = 'Match saved.' success_url = reverse_lazy('backgammon-index') match_form.html {% load crispy_forms_tags %} <div class="container bg-light"> <form method="post"> {% csrf_token %} <div class="modal-body"> {% for field in form %} <div class="form-group{% if field.errors %} invalid{% endif %}"> {{ field|as_crispy_field }} </div> {% endfor %} </div> <div class="modal-footer"> {% if object %}<a class="btn btn-danger mr-auto" href="{% url 'match-delete' pk=object.pk %}">Delete</a>{% endif %} <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="submit-btn btn btn-primary">Save</button> </div> </form> </div> Traceback: Traceback (most recent call last): File "C:\Users\harla\Anaconda3\envs\djangoenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\harla\Anaconda3\envs\djangoenv\lib\site-packages\django\core\handlers\base.py", line 202, in _get_response … -
how i can play a downloaded audio file in response with django
Hello everyone I wanted to give in response an audio file downloaded from youtube but when I go to the page as a client I get a 40kb file I thought that my file was not downloaded whole. Please how can I fix this problem? thank you in advance. here is the code def data(request): """ docstring """ url = "https://www.youtube.com/watch?v=QtTR-_Klcq8" video = pafy.new(url) audiostreams = video.audiostreams audio = audiostreams[3].download() response = HttpResponse(audio, content_type='"Content-Type: audio/mpeg"') response['Content-Disposition'] = 'attachment; filename="audio.m4a"' return response -
Custom User with "USERNAME_FIELD" non-unique in Django
Situation: We have an existing system where current employee logins to the system using their mobile number. But as same mobile number can be used by multiple users, so there is constraint in existing db that, at any moment there can be only one user with given "Mobile Number" and "is_active: True" (i.e their may be other employees registered with same number earlier, but their status of "is_active" would have changed to "false", when they left). Also, only admin can add/register new employees/user. I have created a custom "User" model and "UserManager" as below: models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils.translation import gettext_lazy as _ from .managers import UserManager # Create your models here. class User(AbstractBaseUser, PermissionsMixin): """ A class implementing a fully featured User model. Phone number is required. Other fields are optional. """ first_name = models.CharField(_('first name'), max_length=50, null=True, blank=True) last_name = models.CharField(_('last name'), max_length=50, null=True, blank=True) phone = models.CharField( _('phone number'), max_length=10, null=False, blank=False, help_text=_('Must be of 10 digits only') ) email = models.EmailField(_('email address'), null=True, blank=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user is a staff member.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates … -
Django not picking up overridden translation for third-party applications
I have a third-party application installed which has translation tags in its templates and also provides translations for those in several languages, but I'd like to change a few translations for only one language. I ran the makemessages command and the msgid's for those third-party application show up nicely in my own .po file in the folder I use as LOCALE_PATHS. Then, I added corresponding msgstr's for them, ran compilemessages and expected my translations to override the ones that were provided by the third-party application, but I still see the ones provided by the application. I tried everything up to restarting the webserver, rebuilding the Docker images that I'm using, etc. etc., but I only get to see my own translations once I remove the application's .mo file, which does indicate that my compilemessages worked as expected, but apparently Django is giving preference to the application's .mo file instead of mine, despite the Django docs stating that the language coming from my LOCALE_PATHS should have the highest precedence. What am I missing here? -
HTML (in Django) not accessing Postgresql after changing from SQLite
Was making a mock blog and was initially using the default database for Django (SQLite). Code was works with SQLite but when transferring over to PostgreSQL database no longer shows on HTML. Admin page seems to load of database fine though so I'm assuming it doesn't have to do with Django logging into database. It might be my views.py but at this point I can't seem to find a solution. Any help would be appreciated! Code down below models.py from django.db import models from django.contrib.auth.models import User STATUS = ( (0, "Draft"), (1, "Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) # Create your models here. views.py from django.views import generic from .models import Post from .forms import CommentForm from django.shortcuts import render, get_object_or_404 class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') #context_object_name = 'post_list' template_name = … -
django.db.utils.OperationalError: 3780, "Referencing column and referenced column in foreign key constraint 'S%' are incompatible."
I am trying to migrate all my changes to my development server. I created makemigrations and it was successful but when I try to run "python manage.py migrate" I am facing the below error. Running migrations: Applying hotline.0002_auto_20201023_1559...Traceback (most recent call last): File "C:\Users\Envs\my_glen\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\Envs\my_glen\lib\site-packages\django\db\backends\mysql\base.py", line 74, in execute return self.cursor.execute(query, args) File "C:\Users\Envs\my_glen\lib\site-packages\MySQLdb\cursors.py", line 209, in execute res = self._query(query) File "C:\Users\Envs\my_glen\lib\site-packages\MySQLdb\cursors.py", line 315, in _query db.query(q) File "C:\Users\Envs\my_glen\lib\site-packages\MySQLdb\connections.py", line 239, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (3780, "Referencing column 'outlet_id' and referenced column 'outlet_id' in foreign key constraint 'outlet_distributor_r_outlet_id_6a1221a8_fk_outlet _de' are incompatible.") models.py class OutletDistributorRelation(models.Model): mapping_id = models.CharField(max_length=15, unique=True, null=True) outlet = models.ForeignKey( outlet_detail, on_delete=models.CASCADE, related_name="parent_outlet") distributor = models.ForeignKey( Distributor, on_delete=models.CASCADE, related_name='parent_distributor') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'outlet_distributor_relation' def __str__(self): return str(self.outlet) + "-" + str(self.distributor) Migrations file after running makemigrations migrations.CreateModel( name='OutletDistributorRelation', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('mapping_id', models.CharField(max_length=15, null=True, unique=True)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], options={ 'db_table': 'outlet_distributor_relation', }, ), migrations.AddField( model_name='outletdistributorrelation', name='distributor', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='parent_distributor', to='hotline.Distributor'), ), migrations.AddField( model_name='outletdistributorrelation', name='outlet', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='parent_outlet', to='discount_manager.outlet_detail'), ) I don't know the reason why but the distributor Id is getting migrated but the outlet Id is not. … -
Django messages not showing up on redirects, only render
For a couple days now, I've been trying to figure out why my messages don't show up on redirects. All of the dependencies are there in my settings.py file as you can see. I don't think that's the problem because I am getting two messages to show up on signup and login if the user's passwords don't match on signup or if the user enters the wrong password on login. I notice it only works on renders, but not on redirects. I'll post an image of my file structure and also the relevant files next. File structure images: settings.py from django.contrib.messages import constants as messages MESSAGE_TAGS = { messages.DEBUG: 'alert-info', messages.INFO: 'alert-info', messages.SUCCESS: 'alert-success', messages.WARNING: 'alert-warning', messages.ERROR: 'alert-danger', } INSTALLED_APPS = [ ... 'django.contrib.messages', ... ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', ... 'django.contrib.messages.middleware.MessageMiddleware', ... ] TEMPLATES = [ ... 'context_processors': [ ... 'django.contrib.messages.context_processors.messages', ], }, }, ] My urls.py in the main virtual_library folder from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from book.views import * urlpatterns = [ path('admin/', admin.site.urls), # Book paths path('', include('book.urls')), # Added Django authentication system after adding members app path('members/', include('django.contrib.auth.urls')), path('members/', include('members.urls')), ]+ static(settings.MEDIA_URL, … -
How to use Django iterator with value list?
I have Profile table with a huge number of rows. I was trying to filter out profiles based on super_category and account_id (these are the fields in the model Profile). Assume I have a list of ids in the form of bulk_account_ids and super_categories list_of_ids = Profile.objects.filter(account_id__in=bulk_account_ids, super_category__in=super_categories).values_list('id', flat=True)) list_of_ids = list(list_of_ids) SomeTask.delay(ids=list_of_ids) This particular query is timing out while it gets evaluated in the second line. Can I use .iterator() at the end of the query to optimize this? i.e list(list_of_ids.iterator()), if not what else I can do? -
Djnago Concat Query Error You might need to add explicit type casts
I am trying to query/filter with annotating generated date field. This is my query: trip = Booking.objects.annotate( end_date=Concat( Extract('start_date', 'year'), Value('-'), Extract('start_date', 'month'), Value('-'), Extract('start_date', 'day') + F('itinerary__days') , output_field=DateField() ) ) expired = booking.filter(end_date__gte=datetime.today()) But fires me the following error: HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. I have researched about this and the error is related with PostgreSQL. I am not getting how to fix this these are my models: class Itinerary(models.Model): days = models.PositiveSmallIntegerField(_("Days"), null=True, blank=True) class Booking(models.Model): itinerary = models.ForeignKey( Itinerary, on_delete=models.CASCADE ) start_date = models.DateField(_("Start Date"), null=True, blank=True) def get_end_date(self): return self.start_date + datetime.timedelta(days=self.itinerary.days) I am not getting how to solve this. I don't have fields named end_date but i am making end_date with annotating with increasing the days from the itinerary table Can anyone tell me what is the possible reason my query not working? -
Uploading multiple photos via django admin
I found an interesting option to upload multiple images in the admin area at a time. I try to do the same for myself. models.py from django.db import models class Album(models.Model): name_album = models.CharField('name album', max_length=50) class Image(models.Model): image_prezents = models.ImageField('Photo', null=True, blank=True, upload_to="media/") album = models.ForeignKey(Album,on_delete=models.CASCADE, related_name='album') admin.py from django.contrib import admin from.models import Image, Album class PhotoInline(admin.StackedInline): model = Image extra = 0 class ImageAdmin(admin.ModelAdmin): inlines = [PhotoInline] def save_model(self, request, obj, form, change): obj.save() for afile in request.FILES.getlist('photos_multiple'): obj.photos.create(image=afile) ##????? admin.site.register(Album, ImageAdmin) And I just can't figure out what's in the line obj.photos.create (image = afile) for the photos parameter. Tell me please. I am new to django. -
local variable 'all_inf' referenced before assignment
i am new in django. so i am trying to create a CRUD application using Django but I am getting "local variable 'all_inf' referenced before assignment " this error while trying to build it here is my view.py -- coding: utf-8 -- from future import unicode_literals from django.shortcuts import render from .forms import Create from enroll.models import User Create your views here. def add_show(request): if request.method == 'POST': crt = Create(request.POST) if crt.is_valid(): username = crt.cleaned_data['name'] useremail = crt.cleaned_data['email'] user_contact = crt.cleaned_data['contact_number'] save_to_db = User(name=username, email=useremail, contact_number=user_contact) save_to_db.save() crt = Create() else: crt = Create() all_inf = User.object.all() return render(request, 'index.html', {'form': crt, 'info': all_inf}) -
Deployment of client environment on registration
I want to deploy a django app per client whenever a new client registers. For registration i also have a django app where clients can register (running in a kubernetes namespace) such that after registeration of a client inside the django register app, the actual django app environment for the client is deployed. I would like to automate this process in such a way: As soon as customer registers in the register app, the customer registration data from django register app is transferred to the newly created client django app environment. Any broad ideas or concepts on how to achieve this? -
l'm receiving a broken password reset link when using django.contrib .... reset email
from django.urls import path, NoReverseMatch from django.conf import settings from django.contrib.auth import views as auth_views from django.urls import path, include from . import views urlpatterns = [ path('', views.index, name='index'), path('login.html', views.login2, name='login2'), path('register.html', views.register, name='register'), path('logoutUser', views.logoutUser, name='logoutUser'), path('music.html', views.music, name='music'), path('profile.html', views.profile, name='profile'), path('reset_password/', auth_views.PasswordResetView.as_view(template_name="password_reset.html"), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="password_reset_done.html"), name="password_reset_complete"), path('oauth/', include('social_django.urls',namespace='social')), ] so I'm using this default password reset in Django and l get to send the email and receive it but the problem is that the reset link that will redirect me to the form is broken the port is missing, and if l fix the port in the URL after l click it works and takes me to the password_reset_confirm this is the reset link l receive http://localhost/reset/MQ/ac5zx3-f826598ef65286489c632fd68ecb1175/ -
How to use Django ORM with Panel?
Summary I want to implement an interactive dashboard using panel in a Django application using data from a database. First I've followed the example in the panel docs and it's working fine in my Django project. In that example, the data is calculated in a simple function and a plot is displayed. I can use the widgets and get the expected results. For my application, instead of calculating the data without external dependencies, I want to aggregate data from a database depending on a date range which is chosen by the user in the UI. So I have to gather this data inside the param.Parametrized instance, as far as I understand. Therefore I've tried to use a query on the database ORM instead of calculating values. What I've tried In order to keep it simple here and to stay with the example, I've created a model for the sine values in my Django app (called dashboard): from django.db import models class SineValue(models.Model): x = models.FloatField() y = models.FloatField() and inserted some values: DELETE FROM dashboard_sinevalue; INSERT INTO dashboard_sinevalue (id,x,y) VALUES (1,1,1); INSERT INTO dashboard_sinevalue (id,x,y) VALUES (2,2,4); INSERT INTO dashboard_sinevalue (id,x,y) VALUES (3,3,9); Then I've replaced the calculation of the … -
Serializer behaviour with null=False fields in DRF
I've encountered a weird behavior that I don't quite get. For the model class Tenant: name = models.CharField(max_length=155) country = models.CharField(max_lengh=155) I'm using this serializer: class Serializer(serializers.ModelSerializer): class Meta: model = Tenant fields = (name,) This set up will allow me to save a tenant instance that doesn't have a country supplied even though the null=True should be enforced on the DB level (Postgres). Only when I add country to the fields, will it enforce the null=False constraint. This seems quite unintuitive to me. -
Django IIS - why is my website not loading?
I have been following these videos to get my Django website running using Python FASTCGI Handler in Internet Information Services. All seems OK however when I browse to the website it simply returns the Internet Information Services homepage. Does anyone have any ideas? If you need further information please detail this and I will be sure to post any coding. https://www.youtube.com/watch?v=CpFU16KrJcQ https://www.youtube.com/watch?v=APCQ15YqqQ0 Best, Neil -
Django: Assign Route to Order Based on User Input of Location
In my create order view, I am trying to automatically assign the respective route based on the location the user inputs. Basically, every location in the system has a FK to a route. There are many locations within a route. If you select a location to send products to, the route should automatically be tied to. Currently I am able to see the route for an order in my order_list.html page...but when I view the order in the Django admin...the route is not assigned to the order but the location is. I want it to work similarly to how you would assign the current logged in user to an order: form.instance.user = request.user I tried using: form.instance.company = request.user.company But I am getting an attritbute error: " 'WSGIRequest' object has no attribute 'location' " Here is my full "order_create" function: orders/views.py: @login_required(login_url='account_login') def order_create(request): """ A function that takes the users cart with products, then converts the cart into an OrderForm. Then saves the form/order to the database. """ cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): form.instance.user = request.user form.instance.company = request.user.company form.instance.route = request.location.route order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], … -
How to generate multiple 'datetimes' within the same day using 'Faker' library in Django?
I need to generate dummy data for two datetime fields. Currently I'm using Faker library to achieve this: date1= factory.Faker('date_time_this_month') date2= factory.Faker('date_time_this_month') This generates dummy data of 'datetime' type but I want the date to be same in both the fields and the time of date2 must be greater than the date1. Simply put, I need to generate two 'datetime' type data within same day where date1 < date2.