Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IP error: fjango app not deploying with docker
I am new to Docker so I'm probably missing something obvious but here goes. I am trying to test a simple Django app with docker postgres. All I want right now is to verify that the home page is working on localhost. Debug output window gives me the following: web_1 | System check identified no issues (0 silenced). web_1 | April 28, 2020 - 17:06:23 web_1 | Django version 3.0.5, using settings 'app.settings' web_1 | Starting development server at http://0.0.0.0:8000/ web_1 | Quit the server with CONTROL-C. However when I go to 0.0.0.0:8000 I get an error that says the site can't be reached "The webpage at http://0.0.0.0:8000/ might be temporarily down or it may have moved permanently to a new web address. ERR_ADDRESS_INVALID Here is my docker-compose.yml: version: '3.7' services: web: build: . command: python /app/manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - 8000:8000 depends_on: - db db: image: "postgres:latest" ports: - "5432:5432" environment: - "POSTGRES_HOST_AUTH_METHOD=trust" Here is my dockerfile: # Pull base image FROM python:3.8 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /app # Install dependencies COPY requirements.txt requirements.txt RUN pip install -r requirements.txt # Copy project COPY . /app/ … -
unsupported operand type(s) for -: 'str' and 'datetime.datetime' - from models
I get an error in my models.py file. class TimeAnswerElement(models.Model): email = models.EmailField() costumer_time = models.DateTimeField() my_time = models.DateTimeField(auto_now_add=True) time_compartment = models.DateTimeField(blank=True, null=True) #helped function def save(self, *args, **kwargs): super().save(*args, **kwargs) TimeAnswerElement.objects.filter(pk=self.pk).update(time_compartment=self.field_compartment_function()) def field_compartment_function(self): time = self.costumer_time - self.my_time return time I am trying to subtract two fields that are correctly saved in the model through my view. Why raises my error. in my object where I use properties to override time_compartment, I don't have a string. I have correctly saved date. My views.py if request.method == 'POST' and 'save' in request.POST: form = NewTimeForm(request.POST) if form.is_valid(): cd = form.cleaned_data object = form.save(commit=False) my_date = '%s %s' %(date, cd['time']) object.costumer_time = my_date object.save() else: form = NewTimeForm() How to subtract two dates correctly by property. Do I have to use something like this for my fields? s = "2014-04-07" datetime.datetime.strptime(s, "%Y-%m-%d").date() Or is there a better way to solve this? -
Django: issue with loading static in deployment
I know this question has similar ones but nothing has been able make it for me. My static files are not loading although I feel like have followed the procedure well. I am hoping that a pair a fresh eye could spot the detail that I am missing urls.py .... if settings.DEBUG: setting.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) public_urls.py .... if settings.DEBUG: setting.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static') MEDIA_URL = '/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') STATICFILES_DIRS = [os.path.join(BASE_DIR, "staticfiles"), ] and then what is in /etc/nginx/sites-enabled/django.conf server { listen 80; server_name 35.180.131.203; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/exostocksaas/app.sock; } location /staticfiles/ { autoindex on; root /home/ubuntu/exostocksaas/inventory4/staticfiles/; } } and my errors are that the static files are not loading: GET http://35.180.131.203/css/sb-admin-2.min.css net::ERR_ABORTED 404 (Not Found) and the same for all the statics Am I missing something obvious here, I am out of things to try and any help would be welcome -
How pass a td value from html template to my views.py
Am fairly new to django, so trying to play around with django and learn at the same time by building a small project. Basically I have the below code in my html template: <tbody> {% for items in queries %} <tr> <td>{{ items.ana_user }}</td> <td class="text-center">{{ items.ana_public }}</t> <td>{{ items.ana_private }}</td> <td class="text-center">{{ items.ana_bytestx }} MB</t> <td>{{ items.ana_bytesrx }} MB</td> <td class="text-center">{{ items.ana_policy }}</t> <td>{{ items.ana_duration }}</td> <td class="btn-group"> <button class="btn btn-secondary btn-sm dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Options </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href="{% url 'stats' %}">View Live Graph</a> <a class="dropdown-item" href="{% url 'disconnect' %}">Disconnect Users</a> </div> </td> </tr> {% endfor %} </tbody> Basically by clicking any of the dropdown action. I want to take the value of the first td which is 'items.ana_user' and pass this to my views.py as a 'request.POST.get'. Your help is very much appreciated as usual. -
Can you trigger a signal upon partial update of django object via the django rest framework?
I started noticing that the patch method in django rest framework doesn't actually trigger signals, post methods seem to work fine. This is what I have: @receiver(signals.pre_save, sender=Example) def populate_time_fields_based_on_state(sender, **kwargs): example = kwargs.get('instance') if example.start_datetime is None and example.projected_end_datetime is None and example.state.label == 'Assigned': example.start_datetime = datetime.datetime.now() example.projected_end_datetime = example.created_datetime + datetime.timedelta( days=example.som_field) example.save() And I'm testing this via: client = APIClient() client.patch(f'/api/example/1/', {'state': 'Assigned'}) Is there a way to tell it to trigger the signal? Do I need to override the update method in my serializer? -
Function has no objects member pylint
I am using django 3 i am getting Function product has no object member error in this objects.all() method in my views.py file can anyone help please from django.db import models from django.shortcuts import render from django.http import HttpResponse # Create your views here. from .models import models def pro(request): pro = **product**.objects.all() return render(request , 'accounts/pro.html' , {'product' : pro}) MODELS.PY class product(models.Model): CATEGORY= ( ('InDoor' , 'InDoor'), ('OutDoor' , 'OutDoor'), ) name= models.CharField(max_length = 245 , null=True) price= models.FloatField(null = True) category= models.CharField(max_length=245 , null=True , choices = CATEGORY) description=models.CharField(max_length=500 , null= True , blank=True) date_created=models.DateTimeField(auto_now_add=True , null = True ) tags=models.ManyToManyField(tag) def __str__(self): return self.name -
Django restricting access
How do I restrict user from going on logout page. For example in my project I have a logout page with url logout/. So if a type /logout/ in my address bar it takes me to that page which is meaningless. So how do I make it so only when user click on logout button then only it shows that logout page.(my login-logout system works fine just that I am not able to restrict users from accessing that logout page simply by typing logout/) -
Uncaught TypeError: Cannot read property 'ajax' of undefined in GeoJson Leaflet
I am using ajax query for geoJson data. However, I am not able to load the data into the leaflet maps. Using a sample ajax query such as this, when I look in the console I am able to find the data. Not sure what I am doing wrong. Any help will be greatly appreciated :) Thanks. [ $.ajax({ type: 'GET', url: 'location', //data: { get_param: 'value' }, dataType: 'json', success: function (data, status) { console.log(data); geojson = data } }); function our_layers(map,options){ var Location = L.geojson.ajax("{% url 'location' %}",{ }); }; ]1 -
Ajax call to populate form fields django from with a click button return
I would like to fill my django field form the return of the click button function. The reason of doing that is to allow both manual and the click button options. the click button function collects readings from a serially connected device. how can I use the ajax call for this purpose - appreciate your help. a screen shot of my page enter image description here -
Get Images from Request in Django
I have the following data in request.data <QueryDict: {'eventID': ['1'], 'image_0': [<InMemoryUploadedFile: Bohr.jpg (image/jpeg)>], 'image_1': [<InMemoryUploadedFile: ptcl.png (image/png)>], 'image_2': [<InMemoryUploadedFile: PTCL.jpg (image/jpeg)>], 'image_3': [<InMemoryUploadedFile: ptcll.png (image/png)>]}> This is my code which I am using to get the values but it works only there is only one value of an image. def AddGallery(request): status={'ErrorCode':-1,'ErrorMsg':'Initial-request Add images'} context = {} try: print (request.data) event = request.data.get('eventID', None) image = request.data.get('image', None) usr_mgmt =UserAuthenticationA() status = usr_mgmt.AddGallery(event, image) except Exception as e: print (str(e)) context.update(status) return Response(context) I need the solution with which I can extract the multiple images. Thanks in Advance!!!! -
Dynamic DOM update breaks Django Endless Pagination
I'm using Django EL(Endless) Pagination to emplement a lazy-loading Twitter style pagination on my website. Everything works well. But I'd like my users to be able to dynamically delete some of the paginated results on a button click. So I added this ajax call: $("main").on("click", ".close", function() { let id = $(this).attr("id"); $.ajax({ url: urltomydeleteview, timeout: 0, method: 'POST', }) .done((res) => { $(this).closest('div.col-sm-12').remove(); ... other DOM manipulations .... }) }); That creates a bug, of course: if a user delete several elements and reaches the bottom of the page, the lazy pagination is called with wrong parameters and I got a 404. How can I tell Django EL that my queryset has changed without reloading my page? -
How safe it is to pass a model-object ID as a parameter in a request?
I'm new to web development, so here's the situation: I have a model named Qualifier, that has a name and several other fields. It has a reference to 1 and only 1 User, but doesn't have any other unique fields. e.g.: class Qualifier(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=32) other_field = models.IntegerField(default=0) I also have a view that loads, in a list, all Qualifier objects that belong to the accessing User: they are fetched by the fields user since there's no other "unique field" to distinguish. def qualifiers_view(request): # Access Restriction if not request.user.is_authenticated: return redirect("accounts:login") # Fetch company users qualifiers = Qualifier.objects.filter( user=request.user ) return render(request, 'qualifiers.html', {'qualifiers': qualifiers}) But here's a problem: In the view template, within each row of this list, beside each Qualifier, there's a DELETE button (a "POST" form) intended to call a view that deletes that same Qualifier, based on the parameter(s) passed... but it seems inefficient to me to pass user and name as the parameters, because it would result in another search through the database to find it. I thought: An other option would be to get the Qualifier object's ID's in the DB upon the first search (when the list … -
Should I use StreamingHttpResponse or should I simply send multiple requests to the server?
I am working on a Django project and I need some help deciding which paradigm to use. I don't know how Django behaves in a production since this is the first project that I am intending to release. I am currently using StreamingHttpResponse in Django alongside JavaScript Fetch and ReadableStream APIs to send data from the server to the client over a long period of time. How the app works is that the server is responsible for repeatedly running a simulation (separate to Django), which reports its progress to my Django app. When a client connects , the client sends a request to Django for the progress info and while the simulation is running , Django opens a stream (StreamingHttpResponse) and periodically sends that progress information of the simulation back to the client-- which then shows a progress bar in the browser. The simulation can take hours to complete. I am inexperienced , so the way I tested this (using the development server mind you ) , is to simply open a ton of tabs and point them to the app. Django only allows six of those tabs to connect at a time and only when the stream closes for … -
What can I do to make this function work?
I wrote this login function with a recaptcha but it doesn't work. def LogIn(request): if request.user.is_authenticated: return redirect('home') elif request.method == 'POST': form = AuthenticationForm(request.POST) if form.is_valid(): recaptcha_response = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = {'secret': settings.RECAPTCHA_SECRET_KEY,'response': recaptcha_response} data = urllib.parse.urlencode(values).encode() req = urllib.request.Request(url, data=data) response = urllib.request.urlopen(req) result = json.loads(response.read().decode()) username = request.POST['username'] password = request.POST['password'] if (result['success']) and (result['action'] == 'login'): messages.success(request, "Welcome") user = authenticate(request, username=username, password=password) login(request, user) return redirect('home') else: messages.error(request, 'Invalid reCAPTCHA. Please try again.') else: form = AuthenticationForm return render(request, 'login.html', {'form': form}) the recaptcha works, I tried it with the signup function and it works so it's not the recaptcha. when I try to login and press the submit button it just refreshes the page. what am I doing wrong here? and if there's some mistakes in my code or something I could learn please tell me I will really appreciate it. thanks -
i can't get the background image .please solve the issue
here are some files from project hope so they help you to fix this error. my setting.py """ Django settings for advice_lancing project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '(71f#n^0en3u1=j=%bthg1m%d2=so=3+@p6=2u+5k)04caf+od' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'markdownx', 'blog', ] 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', ] ROOT_URLCONF = 'advice_lancing.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'advice_lancing.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', … -
m2m relationship in PostgreSQL
I have two models related through a third: class Order(models.Model): parts = models.ManyToManyField(Part, through='invent.UsedPart') class Part(models.Model): class UsedPart(models.Model): part = models.ForeignKey(Part, on_delete=models.CASCADE) order = models.ForeignKey('mtn.Order', on_delete=models.CASCADE) This schema worked ok in SQLite, but when i tried to migrate it to PostgreSQL i get this error: Running migrations: Applying invent.0002_auto_20200428_1105...Traceback (most recent call last): File "/home/vadim/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.DuplicateColumn: column "order_id" of relation "invent_usedpart" already exists Did I define them wrong way? -
How to change language or customize template "password_reset_confirm"
Im using auth_views.PasswordResetView, when user the user receives the email to reset password, he will see the view "auth_views.PasswordResetCompleteView" this view loads the following template: {% extends 'base.html' %} {% load static %} {% block css %} <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> {% endblock %} {% block content %} <br> <br> <br> <br> <br> {% if validlink %} <h3>Change password</h3> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Restablecer</button> </form> {% else %} <p> El link para restablecer tu contraseña es inválido, posiblemente porque ya ha sido utilizado anteriormente. Por favor solicita nuevamente restablecer tu contraseña. </p> <a href="/">Inicio</a> {% endif %} {% endblock %} But the template is in english: ¿Can I change the language of the template? -
When you click on "publish", an error occurs MultiValueDictKeyError at /publish 'secret'
def publish(request): if request.method == 'GET': return render(request, 'publish.html') else: secret = print(request.POST['secret']) name = print(request.POST['name']) text = print(request.POST['text']) publications_date.append({ 'id': len(publications_date), "name": name, "date": datetime.now(), "text": text }) return redirect('/publications') -
Module for model translations in Django
I am trying to find a module that can perform model translations in Django. In the past (very past, I think it was with Django 1.4) I had used django-hvad and it seemed a good choice at this time. Today, I am looking into awesome Django repo in order to choose on of the listed ones, to use in my new project that I build with Django 3. Which one do you think it's the best choice? From a quick look I had, it seems that there is no perfect solution and each of those has its own issues: django-hvad: Last commit was on 18/08/2017 - a looong time ago! Also, it seems to work well for Django < 2.0. For Django 2+, I see lots of issues in the issue tracker. There are some discussions, an effort to make django-hvad2 since 2015 (some of it has been merged into django-hvad) and a recent question: is it dead? but no answer. To me, this seems a dead end, so it's a NO - it's a pity, AFAIR it was very nice back on Django 1.x days. django-klingon: Quick overview seems good, but it hasn't been developed since November 2018 (last … -
Django specific language for each user is not respected
I need to change the default language for each user, but in my case the translation is not applied with the selected language. I store the preferred language for each user and set it as follows: # set default language try: user_language_filter = UserFilters.objects.get(user=request.user, element__iexact='defaultLanguage') user_language = user_language_filter.value.lower() except UserFilters.DoesNotExist: user_language = 'en' if translation.LANGUAGE_SESSION_KEY in request.session: del request.session[translation.LANGUAGE_SESSION_KEY] translation.activate(user_language) request.session[translation.LANGUAGE_SESSION_KEY] = user_language print(translation.get_language()) Here I retrieve the stored language for the user and if not available, set it to 'en'. print() shows the correct language. In my settings I have: MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', .... LANGUAGES = ( ('en', _('English')), ('fr', _('French')) ) LOCALE_PATHS = ( os.path.join(BASE_DIR, '../locale'), ) makemessages and compilemessages create the files correctly in the given path. In my ListView I have: def get_context_data(self, **kwargs): context = super(CompanyListView, self).get_context_data(**kwargs) context.update({ 'page_title': _('Manage Companies'), }) return context The text to translate is in the locale files and also translated. I also printed the {{ LANGUAGE_CODE }} in the template which shows the correct one. But in the template the page_title is not translated. Every help is appreciated. -
How to return value from custom database lookup based on model value in Django admin list_display?
Searched the internet a lot for this, tried many solutions but didn't get it working. I have these models. models.py class Cadastro(models.Model): id_cadastro = models.AutoField(primary_key=True) categoria_tipo = models.CharField("Categoria", max_length=50, null=True) chave = models.CharField("Chave", max_length=50, null=False, blank=False) valor = models.CharField("Valor", max_length=50, null=False, blank=False) escricao_valor_cadastro = models.TextField("Descrição / Observação", blank=True, null=True) class Meta: verbose_name_plural = "Cadastros" def __str__(self): return self.valor class ClasseCNJ(models.Model): cod_item = models.IntegerField(primary_key=True) tipo_item = models.CharField(max_length=1) nome_item = models.CharField(max_length=100) class Meta: managed = False db_table = 'itens' def __str__(self): return self.nome_item class ElementoAutomacao(models.Model): id_automacao = models.AutoField(primary_key=True) elemento_automacao = models.ForeignKey('Elemento', on_delete=models.CASCADE, verbose_name="#Elemento", related_name='elemento_automacao', blank=False) tipo_item = models.ForeignKey('Cadastro', on_delete=models.SET_NULL, related_name='tipo_item', null=True, blank=True, limit_choices_to={'chave': 'DEST'}, verbose_name="Item Tipo") item_codigo = models.CharField(max_length=10, blank=True, null=True, verbose_name="#Código") class Meta: verbose_name_plural = 'Regras de Automação' def __str__(self): return self.elemento_automacao.nome_elemento def get_item_cnj_desc(self, obj): if obj.tipo_item == "Movimento": descr_cnj = ClasseCNJ.objects.get(pk=obj.item_codigo, tipo_item='M') elif obj.tipo_item == "Classe": descr_cnj = ClasseCNJ.objects.get(pk=obj.item_codigo, tipo_item='C') elif obj.tipo_item == "Assunto": descr_cnj = ClasseCNJ.objects.get(pk=obj.item_codigo, tipo_item='A') else: descr_cnj = " - " return descr_cnj get_item_cnj_desc.short_description = 'Descrição' Cadastro model is a generic table that I store key-value data to populate the many listboxes. ElementoAutomacao has tipo_item field that points to Cadastro, filtering the options, so it can have "Movimento", "Classe" and "Assunto" and item_codigo field that stores a … -
What is the preffered way to store model details in django?
I am trying to develop a django application to help keep track of macro- and micronutrients in my diet. So far, I am super happy with the django documentation. But right now I am stuck on a more conceptual question related to databases and model relationships. My current model for an Ingredient and the associated NutrientProfile looks like this: class Ingredient(models.Model): ingredient_id = models.UUIDField( verbose_name="Ingredient", primary_key=True, default=uuid.uuid4, editable=False, ) name = models.CharField(max_length=300, unique=False) synonyms = models.CharField(max_length=300, blank=True, null=True) category = models.CharField(max_length=300, blank=True, null=True) class NutrientProfile(models.Model): nutrientProfileID = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) # Ingredient the NutrientProfile is associated to ingredient = models.ForeignKey( to="Ingredient", related_name='nutrientProfile', on_delete=models.CASCADE, blank=True, null=True, ) fat_total = models.DecimalField(max_digits=7, decimal_places=4, blank=True, null=True) protein = models.DecimalField(max_digits=7, decimal_places=4, blank=True, null=True) cholesterol = models.DecimalField(max_digits=7, decimal_places=4, blank=True, null=True) ... more nutrients So currently I am able to create Ingredients, and associate them with one or more NutrientProfiles. I did not define this relation as One-to-One, because there may be multiple NutrientProfiles for a single ingredient (multiple data sources). Now the issue: I realized, that I will need some more information on each nutrient, such as the unit, a comment, date added,... So I came up with the following models to include such … -
Prefetch related querying django
I need to filter on a attribute I can't get access to. I think I need to use prefetch related but I can't get the right one. Or maybe it's just impossible what I try to do. So I want to filter my History objects on supplier ID. These are the models: class History(models.Model): date = models.DateTimeField(auto_now=True) license = models.ForeignKey( License, on_delete=models.CASCADE, related_name="license_history_list" ) class License(models.Model): code = models.CharField(max_length=25) order_item = models.ForeignKey( OrderItem, on_delete=models.CASCADE, related_name="licenses" ) class OrderItem(models.Model): order = models.ForeignKey( Order, on_delete=models.CASCADE, related_name="order_items" ) product_type = models.ForeignKey( ContentType, on_delete=models.SET_NULL, blank=True, null=True ) class Order(models.Model): reference = models.CharField(max_length=50) supplier = models.ForeignKey( Supplier, on_delete=models.CASCADE, related_name="orders" ) So this is the structure I need to go: History -> license -> orderitem -> order -> supplier When I use the filter command I can go to license__order_item__order, but not longer to license__order_item__order__supplier, I don't know why? How can I solve this? -
Django create a Post collection table from multiple models
I want to create a model class at my django application that stores all UUIDs (primary keys) of all my post models as I have more than one. I saw this post: Copy Model Object Id From a Model To Another Model In Django And created a model class accordingly, currently only with one model instead of multiple: class Post_Collection(models.Model): id = models.BigAutoField(primary_key=True, editable=False) post_model1 = models.ForeignKey(Post_Model1, on_delete=models.CASCADE) def __str__(self): return self.id @receiver(post_save, sender=Post_Model1) def ensure_post_exists(sender, **kwargs): if kwargs.get('created', False): Post_Collection.objects.get_or_create(post_model1=kwargs.get('instance')) Sadly I'm running into th following issue: TypeError: str returned non-string (type UUID) Now my question is how can I setup a model that can store copies of all my primary keys when using multiple post models as soon as a new post has been created? Why do I need this? In order to have a performant DB access when using e.g. random.sample at views.py to query random post entries it makes more sense to accomplish this from one table instead of multiple each time a page gets loaded for the user and I want to display some proposals the user may also like to see. -
BUG: Cannot create a Meal instance with a FK Store instance in the views.py (Django and Django Rest Framework)
I am doing a delivery API REST usign Django and Django Rest Framework. In the Meal app there is a bug that has been for days and I cannot solve it. I do not know how to fix it. Thanks you in advance. This is the bug shown in postman: { "store": [ "Incorrect type. Expected pk value, received Store." ] } Meal/models/meals.py class Meal(models.Model): '''Meals models.''' store = models.ForeignKey( Store, on_delete=models.CASCADE, ) name = models.CharField(max_length=120) slugname = models.SlugField( unique=True, max_length=120, ) description = models.TextField(max_length=300, blank=True) price = models.DecimalField( 'meal price', max_digits=5, decimal_places=2 ) picture = models.ImageField( 'meal picture', upload_to='meals/pictures/', blank=True, null=True, help_text="Price max up to $999.99" ) # Status is_available = models.BooleanField( 'Meal available in menu', default=True, help_text='Show is the items is available for customers' ) # Stats rating = models.FloatField( default=5.0, help_text="Meal's rating based on client califications" ) Meal/views/meals.py class MealViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): '''Meals view set. ''' serializer_class = MealModelSerializer lookup_field = 'slugname' search_fields = ('slugname', 'name') # Method call every time this MealViewSet is instanced def dispatch(self, request, *args, **kwargs): '''Verify that the store exists. Add the URL input <store_slugname> to the Meal model field store(FK). ''' store_slugname = kwargs['store_slugname'] self.store = get_object_or_404(Store, store_slugname=store_slugname) return …