Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AppConfig.ready() is running before the migrations on manage.py test
I am trying to use Django's AppConfig.ready() method to run some some query on one of the models to retrieve some data. I have the following code: class NewsConfig(AppConfig): name = "apps.news" verbose_name = "News" def ready(self): NewsType = self.models.get("newstype") NewsType.names = NewsType.objects.values_list("name", flat=True) then, on urls.py I'm using them as follow: news_type_names_regex = generate_regex(NewsType.names) router = DefaultRouter() router.register(r'news/' + news_type_names_regex, NewsModelViewSet, basename='news') This works fine when the application runs (using uvicorn or runserver), but when running tests, the AppConfig.ready() gets executed before the migrations are run, which results in the following error: ... django.db.utils.OperationalError: no such table: news_newstype I've read the warning on the docs, but I don't think it is related to this issue. The reason why I'm doing this on the AppConfig.ready() is because it needs to be done somewhere after django.setup() but not in an async request context (as I'm using django channels and running the application ASGI). -
Failed To Fetch Error with Django Application
Working on a Django app and running in to a failed to fetch error intermittently from my JS code. You can see the network responses below - where the error is intermittent from the server (currently on localhost:8000) My django server logs are showing nothing - so 'connection refused' and 'empty response' are confusing. On the JS side I am using fetch(data.getAttribute('action'), { method: data.getAttribute('method'), body: new FormData(data), headers:{ "X-CSRFToken": csrf_token, "X-Requested-With": "XMLHttpRequest"}, }).then(res=>res.json()) .then(function (data) { console.log(data) document.getElementById('create-submit-button').style.border = "2px solid #ebebeb" if(data.status == 'success'){ //happy path will be to add photos on good response console.log('happy path') } else { Swal.fire({ icon: 'error', title: 'there was an issue with your request', text: data.message, }) } }) .catch(error => console.log('Error: ', error)) } My django view is as follows: @login_required(login_url='login') def create(request): if request.method == "POST": if request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' and request.user.is_authenticated: print(request.POST) form = SpinForm(request.POST) if form.is_valid(): user = request.user spin = Spin() spin.prompt = form.cleaned_data['prompt'] spin.user = user spin.orientation = form.cleaned_data['orientation'] # save spin to get many to many relationship spin.save() spin.themes.add(*form.cleaned_data['themes']) # update users total spins user.current_spins += 1 user.save() # themes = request.POST.getlist('theme') computed_prompt = '' if len(spin.themes.all()) > 0: for theme in spin.themes.all(): computed_prompt += … -
Django router.register gets called for every request
I'm inheriting this project that has a urls.py which imports a set of urlpatterns as such: # myapp.rest router = routers.DefaultRouter(trailing_slash=True) router.register(r'campaigns', CampaignViewSet, 'campaigns') router.register(r'campaign-search', CampaignSearchViewSet, 'campaign-search') router.register(r'guestbook', GuestBookViewSet) router.register(r'updates', UpdateViewSet) router.register(r'albums', AlbumViewSet) urlpatterns = [ url(r'^api/', include(router.urls)), ] Now in another set of urls, i'm adding some new api endpoints: urlpatterns = [ url(r'^rest_1/campaigns/(?P<filter>\w+)$',views.RestCampaignView.as_view()), ] So my main urls.py looks like: from myapp.rest import urlpatterns as rest_urls # router.register calls urlpatterns = patterns( url(r'^v2/api/', include('hhl.apps.rest_1.urls')), ) urlpatterns += rest_urls Now whenever I call my new rest endpoints, v2/api..., I'm seeing that the myapp.rest urlpatters are re-registered, and it's actually calling each viewset before it's even getting to my new view. This is Django 1.8.9 so it's a bit dated. How can I fix this so that it's not calling every Viewset for every request? -
Run a subprocess and show output in realtime AND log stderr
Yo, I am using python to run a subprocess that takes a while to execute, and that may or may not succeed. My question: How can I keep realtime output of the process AND collect error lines? Thanks Here is my code so far: process = subprocess.Popen("my_cmd", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) complete_err_message = '' while True: output = process.stdout.readline() error = process.stderr.readline() if output == b'' and error == b'' and process.poll() is not None: if complete_err_message != '': # handle err here print(complete_err_message) break if output: print(output.strip().decode('utf-8')) if error: complete_err_message = complete_err_message + '\n' + error.strip().decode('utf-8') That seems to run very well when the process fails. All the error lines are taken in and stored under complete_err_message. However, when the process doesn't fail, I lose the realtime output and the program seems to lock at the error = process.stderr.readline() step. I am guessing this is because the stderr PIPE is empty, but I am not sure and I don't know how to bypass that. -
How can I upload a django application with this libarys in a free server?
Hi I want to deploy one django app project that I did, but I can't, already tried heroku22, PythonEverywhere and more. I also use python-3.10 and the currently windows 11. heroku-22 - Tried as the tutorials said but always dropped error 404. pythoneverywhere - Was the closed one to upload but couldn't download some libarys. -
How to create two table columns (<td>) in html from one context using Django?
I am using dataTables to show my data, It's just names of some places which i want to put in two columns instead of one. I created two tags in table which allowed me to have two columns but i don't know how to effectively populate it and still have normal pagination. Places even_name odd_name even_name odd_name I tried splitting queryset in two (odd and even) and then used zip() on it. That kinda worked but it wouldn't show last set of items because some lists were uneven. If i tried to iterate over longer list with itertools i would get an error because that one pair has an empty element <table data-page-length='15' id="table" class="display" style="width:100%"> <thead> <div class="col-4"> <tr> <th class="text-end erlorefont col-6" style="color:orange">{{ title.0 }}</th> <th></th> </tr> </div> </thead> {% if lore_list|length > 29 %} <tbody> {% for odd, even in zipped_list %} <tr> <td class="erlorefont "><a style="text-decoration:none;" href="{% url 'lores:loreitems' odd.id %}">{{odd}}</a></td> <td class="erlorefont "><a style="text-decoration:none;" href="{% url 'lores:loreitems' even.id %}">{{even}}</a></td> </tr> {% endfor %} </tbody> {% endif %} </table> I expect something like this in case there is uneven number of elements in a zipped item. I want to have two columns per page with 15 … -
Issue: "Page not found (404)"
So when I'm trying to visit the products/add_to_wishlist/ URL, it gives me the error "Page not found 404". I've been in my URLs and it all seems to be fine, I can't find the issue. Here is my code: urls.py (Products app) from django.urls import path from . import views urlpatterns = [ path('', views.all_products, name='products'), path('<int:product_id>/', views.product_detail, name='product_detail'), path('add/', views.add_product, name='add_product'), path('edit/<int:product_id>/', views.edit_product, name='edit_product'), path('delete/<int:product_id>/', views.delete_product, name='delete_product'), path('wishlist/<int:product_id>/', views.add_to_wishlist, name='add_to_wishlist'), path('wishlist/remove/<int:product_id>/', views.remove_from_wishlist, name='remove_from_wishlist'), path('submit_review/<int:product_id>/', views.submit_review, name='submit_review'), ] urls.py (main app): from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('home.urls')), path('products/', include('products.urls')), path('bag/', include('bag.urls')), path('checkout/', include('checkout.urls')), path('profile/', include('profiles.urls')), path('contact/', include('contact.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py: @login_required def add_to_wishlist(request, product_id): product = Product.objects.get(id=product_id) wishlist, created = Wishlist.objects.get_or_create(user=request.user) wishlist.products.add(product) return redirect('wishlist') @login_required def remove_from_wishlist(request, product_id): product = get_object_or_404(Product, pk=product_id) wishlist = Wishlist.objects.get(user=request.user) wishlist.products.remove(product) return HttpResponseRedirect(reverse('wishlist')) wishlist.html {% extends 'base.html' %} {% block content %} <div class="container"> <h1>My Wishlist</h1> <div class="row"> {% if wishlist.products.all %} {% for product in wishlist.products.all %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <div class="card-body"> <h2 class="card-title">{{ product.name }}</h2> <p class="card-text">{{ product.description }}</p> <p class="card-text">$ {{ product.price }}</p> <form action="{% url 'remove_from_wishlist' … -
access-control-allow-headers doesn't change after setting corsheaders djang
This is my middleware settings about Corsheaders and other middleware, and i have installed django-cors-headers an put it into installed_app INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "main", "rest_framework", "rest_framework_simplejwt.token_blacklist", "django_filters", "drf_spectacular", "corsheaders", ] CORS_ALLOWED_ORIGINS = [ "http://hypeandplay.com", ] CORS_ALLOW_CREDENTIALS = True MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", # "hypeandplay.middleware.CustomCorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] i want to input other allow headers, ex: authorization, but i don't know why the response headers didn't change so i got stricted by cors setting Allow_Headers: CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", ] Response from browser: enter image description here i tried to add authentication, but after i add it in the production, it got error cause of cors enter image description here -
Populate readonly nested serializer
Im using ModelViewSets and I have nested serializer for those models class Profile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.CASCADE) place = models.OneToOneField(Place, on_delete=models.DO_NOTHING) bio = models.TextField(null=True) class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(max_length=150, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name'] def __str__(self): return self.email How can I autocomplete a newly created profile with 1:1 relation to User? class UserSerializer(serializers.ModelSerializer): class Meta: model = User exclude = ('password', 'is_superuser', 'is_staff', 'groups', 'user_permissions') class ProfileSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): user = UserSerializer(read_only=True) place = PlaceSerializer(read_only=True) class Meta: model = Profile fields = '__all__' depth = 1 As you can see I'm using 'drf-writable-nested' and it works okay but I can't figure it out how to automatically connect profile to user on new profile creation -
Saving changes in FormSet with related models
Business logic: Two employees. First employee create application with input 'type_car'. Second employee update application input 'reg_mark' and 'brand'. So, on first step i can create application. I have for this 'type_car' select input field with good view, because it get elements from model with str method. But, i can't update application on second step. If i select 'reg_mark' and try save my changes, i get initial application with empty field 'reg_mark'. And additional, for application i get object from model 'Car' with str method 'reg_mark' and it identically show in select fields 'brand' and 'reg_mark'. How i can fix it? Models: class Application(models.Model): reg_mark = models.ForeignKey(Car, ... ) brand = models.ForeignKey(Car, ... ) type_car = models.ForeignKey(TypeCar, ... ) class Car(models.Model): brand = models.CharField(max_length=50) reg_mark = models.CharField(max_length=10) type = models.ForeignKey('TypeCar', ... ) def __str__(self): return self.reg_mark class TypeCar(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title I' using two identically FormSets for input (Add and Close) class ApplicationCloseForm(forms.ModelForm): class Meta: model = Application fields = { 'reg_mark', 'brand', 'type_car', } ApplicationCloseFormSet = modelformset_factory( Application, form=ApplicationCloseForm, extra=0, can_delete=False, ) view for create application def application_add(request): if request.method == 'POST': formset = ApplicationAddFormSet(request.POST or None) if formset.is_valid(): form.save() else: formset = ApplicationAddFormSet(queryset=Application.objects.none()) return … -
Change Display Values for Cloudinary Field in Django Admin
So in my model I have: cloudinary_logo = CloudinaryField('image', blank=True, null=True) In the admin for this model, I list the field in fields. And it displays as such. I'd like to update the name to be "Logo Location" and the description to say something like "drag image file here to upload!" How would you go about doing this? TIA I'm considering a custom method that would allow me to write the html, but I don't want to screw up the functionality of the Cloudinary Field itself, so I'm not sure if this would be the best way. I've written a custom save_model that looks as such: def save_model( self, request: str, obj: Community, form: forms.ModelForm, change: str ) -> None: #check if cloudinary logo was changed super().save_model(request, obj, form, change) if 'cloudinary_logo' in form.changed_data: #move it, rename it moved_file_name = f"{ENV}/logos/{obj.id}-{obj.external_id}-{obj.name}" cloudinary.uploader.upload(obj.cloudinary_logo.build_url(), public_id=moved_file_name) obj.cloudinary_logo = moved_file_name obj.save() -
Body width changes on mobile devices. Footer width changes
When resizing the browsers window. Or when I use the responsive view in the dev tools, after about 600px the body gets smaller. Here is an image of my problem: Somehow the problem only exists in the chrome browser, in the Safari Browser it works. I created a JS Fiddle to show you the problem: https://jsfiddle.net/fpq6nyco/2/ I am pretty sure that the error sits in these lines: @media (max-width: 726px) { .toggle-button { display: inline; } .navbar-links { display: none; width: 100%; z-index: 10; background-color: var(--primary-color); } .navbar { flex-direction: column; align-items: flex-start; } .navbar-links ul { width: 100%; flex-direction: column; } .navbar-links.active { display: flex; } .logo { display: inline; } .navbar-controls { display: flex; flex-direction: row; align-items: center; justify-content: space-between; height: 100%; } .container{ display: flex; flex-direction: column; justify-content: space-around; align-items: center; width: 100%; } .item{ width: 100%; } .info-section{ margin-top: 200px; } .community-cont{ display: flex; flex-direction: column; align-items: center; justify-content: space-around; margin-top: 50px; margin-bottom: 50px; } footer { width: 100%; height: auto; background-color: var(--dark-color); display: flex; flex-direction: column; align-items: center; justify-content: space-around; padding-top: 20px; padding-bottom: 20px; } .item-container { display: flex; flex-direction: column; align-items: center; justify-content: space-around; height: 40vh; } .text-cont-footer { color: var(--primary-color); width: 100%; } … -
Apply an update to a queryset involving a foreign key
Lets say I have something like the code below, where I can nicely apply the update method to change the engine type of the cars contained in the query set vintage_cars. Is it possible to use update in a similar fashion for the code using the for loop, where a foreign key is involved? class Driver(Model): name = CharField() licence = CharField() class Car(Model): driver = models.ForeignKey(Owner) status = CharField() type = CharField() engine = CharField() vintage_cars = Car.objects.filter(type="vintage") vintage_cars.update(engine="gas") for c in vintage_cars: driver = c.driver if driver and driver.licence not in VALID_LICENCES: c.driver = None c.status = "IMPOUNDED" d.save() I'm thinking I need to apply a second filter involving this clause: if driver and driver.licence not in VALID_LICENCES: to vintage_cars, but I'm not sure if that makes sense in terms of efficiency. -
I can access Django server directly despite nginx reverse proxy
I have a Django Rest Framework server running with Gunicorn with this command : gunicorn --bind 0.0.0.0 --forwarded-allow-ips="*" partyapp.wsgi:application --access-logfile - --error-logfile - --log-level debug I have Nginx as a reverse proxy with the following configuration: server { listen 80; server_name 162.19.70.85; location /static/ { root /var/www; } location = /favicon.ico { access_log off; log_not_found off; } location / { proxy_pass http://localhost:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } It is working well: I can access the service with http://{IP} but also with http://{IP}:8000 which hits Django server directly. I don't think it is a good behavior and I want people to be "forced" to go through the reverse proxy. How can I do that ? Thanks. -
Uneven and unfair fight against JavaScript
Hey i need a help in JS organization. I working on project in Django and now i have moment that i can't jump at all. I have a site where the form of inputs is on many sites one after another. For now i have some JS written in witch i can move on sites but the real problem IS: I need to take data ('Categories') from checkbox in first step and this decide what data will show on step three where should show up only Institutions which have the same categories. Then in step 4 i user give the adress etc. and in step 5 (Summary) data from steps before should shown on screen. In step 5 is a button confirm to send data back to Django Please help my mental health Models from django.db import models from django.contrib.auth.models import User FUNDATION_TYPE = ( (1, 'Fundacja'), (2, 'Organizacja pozarządowa'), (3, 'Zbiórka lokalna'), ) class Category(models.Model): name = models.CharField(max_length=64) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Institution(models.Model): name = models.CharField(max_length=128) description = models.CharField(max_length=256) type = models.IntegerField(choices=FUNDATION_TYPE, default=1) categories = models.ManyToManyField(Category) class Meta: verbose_name_plural = "Institutions" def __str__(self): return self.name class Donation(models.Model): quantity = models.IntegerField() categories = models.ManyToManyField(Category) … -
Django HTML Select not loading correct option
Im having some trouble at my first Django project. I have a ListView in which I have several comboboxes (select) to filter data in a table. Im using Foundation for my site The problem I´m having is that once I establish the "filters" for the queary in my comboboxes, data is presenting fine, but after loading the table, one of the selects is not loading the correct option(last lookup) This is my ListView code: class ListSales(LoginRequiredMixin, ListView): template_name = "sales/list.html" context_object_name = 'sales' login_url = reverse_lazy('users_app:user-login') paginate_by = 5 def get_queryset(self): client = self.request.GET.get("clientselect", "") payment_method = self.request.GET.get("paymentselect", "") date1 = self.request.GET.get("date1", '') date2 = self.request.GET.get("date2", '') product = self.request.GET.get("productselect", '') if date1 == '': date1 = datetime.date.today() if date2 == '': date2 = datetime.date.today() queryset = Sale.objects.get_sales_list( date1, date2, client, payment_method) qty_total_product = 0 if product != '0' and product != '': print(Product.objects.get(id=product).full_name) print(queryset) for querysale in queryset: print(querysale) for query_sale_detail in querysale.sale_details(): print(query_sale_detail.product.full_name + " " + str(query_sale_detail.count)) if str(query_sale_detail.product.id) == product: qty_total_product += query_sale_detail.count print(qty_total_product) obj_sales_list_filter, created_obj_sales_list_filter = SalesListFilters.objects.get_or_create( id=1, defaults={ 'datefrom': date1, 'dateTo': date2, 'client': Client.objects.search_id(client), 'payment_method': PaymentMethod.objects.search_id(payment_method) }) if not created_obj_sales_list_filter: obj_sales_list_filter.datefrom = date1 obj_sales_list_filter.dateTo = date2 obj_sales_list_filter.client = Client.objects.search_id(client) obj_sales_list_filter.payment_method = PaymentMethod.objects.search_id( payment_method) obj_sales_list_filter.save() … -
Using a DRF JSONField as a Serializer
I have a custom JSONField which I would like to use as a serializer. Serializers provide a bunch of extra functionality that you don't get with a Field. Serializers are Fields but not the other way around. As an example, consider a field which has some complex dynamic data and needs to be validated manually: from rest_framework.serializers import JSONField, Serializer class MetadataField(JSONField): def to_internal_value(self, raw_data): data = super().to_internal_value(raw_data) # lengthy validation logic which is calling other methods on the class return data class ItemSerializer(Serializer): metadata = MetadataField() To keep this field reusable and to prevent bloating the ItemSerializer class we move the logic out into its own MetadataField. However, as a consequence, we no longer have access to things like self.instance, nor can we directly instantiate this class like a serializer and pass it some data. Generating a dynamic schema is not an option, and I would like if at all possible to keep the validation logic out of ItemSerializer. -
Universal method to merge duplicate objects in Django
I want to write a universal class to merge duplicate entries in django reassigning all many-to-one and many-to-many references from old to new object. Something like this: def form_valid(self, form): new_object = self.model.objects.get(id=form.cleaned_data['inst'].id) old_object = self.model.objects.get(id=self.kwargs['pk']) for obj in old_object.machine_set.all(): obj.company = new_object obj.save(update_fields=['company']) for obj in old_object.contact_set.all(): obj.company = new_object obj.save(update_fields=['company']) for obj in old_object.partquote_set.all(): obj.company = new_object obj.save(update_fields=['company']) for obj in old_object.trip_set.all(): obj.company = new_object obj.save(update_fields=['company']) for obj in old_object.address.all(): new_object.address.add(obj) for obj in old_object.email.all(): new_object.email.add(obj) for obj in old_object.phone_number.all(): new_object.phone_number.add(obj) if not new_object.website and old_object.website: new_object.website = old_object.website new_object.save(update_fields=['website']) if not new_object.comments and old_object.comments: new_object.comments = old_object.comments new_object.save(update_fields=['comments']) return redirect(new_object.get_absolute_url()) But I don't want to hard-code it manually for all related fields. Instead I want to do something like this: def form_valid(self, form): new_object = self.model.objects.get(id=form.cleaned_data['inst'].id) old_object = self.model.objects.get(id=self.kwargs['pk']) for related_object in self.model._meta.related_objects: for obj in related_object.SOMEHOW_GET_QUERYSET(): // Assuming the field we are looking for is lower case model name SOMEHOW_GET_FIELD_FROM_SELF_MODEL = new_object obj.save(update_fields=['SOMEHOW_GET_FIELD_FROM_SELF_MODEL']) for related_object in self.model._meta.many_to_many: for obj in related_object.SOMEHOW_GET_QUERYSET(): new_object.SOMEHOW_GET_FIELD_FROM_RELATED_OBJECT.add(obj) Is it posssible to do something like that? -
How to create multiple models from a single endpoint w/ Django
I want to have an single endpoint that accepts a POST request and creates an "Order" that can be one of two types. The User should be able to submit an order (of either type) as JSON, and create a new Order. Behind the scenes, two models are created. One "Base Order" Model that describes some common characteristics, and one "Type A Order" or "Type B Order" that describes the characteristics specific to that order. The actual order types and their fields will be vastly more complicated so here are just described as A and B with a few charFields. The general idea though is that the same endpoint is used to create two models, a BaseOrder model, and a model of a type determined by the order_type field submitted. I think the conditional part of this (which order to make) should not be too difficult. But I'm unsure how to create two separate models from the same endpoint, even if it was always of the same type. Models: class BaseOrder(models.Model): name = models.CharField(max_length=80) timestamp = models.DateTimeField(null=False) class OrderType(models.TextChoices): TYPEA = "A", "Placeholder A" TYPEB = "B", "Placeholder B" order_type = models.CharField( max_length=16, verbose_name="Order Type", choices=OrderType.choices, ) class TypeAOrder(models.Model): a_field1 … -
How do I fix Django returning 'self' not defined NameError on queryset filtering of ModelChoiceField?
I have 2 models, Type and Measure. Each Measure object has a typeid ForeignKey field that refers to the id field of a Type object. Each Type is viewed on it's own page where the id is passed through URL. urls.py urlpatterns = [ path('type/<int:id>', views.type, name='type'), ] The view had been working with this as it is before I added the ModelChoiceField to the form. views.py def type(request, id): mytypes = Type.objects.all().values() mytype = Type.objects.get(id=id) mymeasures = Measure.objects.filter(typeid=id) template = loader.get_template('type.html') if request.method == 'GET': form = ConvForm(request.GET) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: if request.from_type != None: redir = f"/type/{id}" # create a form instance and populate it with data from the request: return HttpResponseRedirect(redir) # if a GET (or any other method) we'll create a blank form else: form = ConvForm(id) context = { 'form' : form, 'mytype': mytype, 'mytypes' : mytypes, 'mymeasures' : mymeasures } return HttpResponse(template.render(context, request)) It is once it imports the form that it runs into a problem with the following code. forms.py class ConvForm(forms.Form): from_value = forms.DecimalField(label='From Value', max_digits=256, decimal_places=255) from_measure = forms.ModelChoiceField(queryset=Measure.objects.none()) class __init__(self, … -
Django admin panel: select a group in many to many list
I have 3 models as follows: class ColorGroup(models.Model): name = models.CharField(max_length=255) class Color(models.Model): color_group = models.ForeignKey(ColorGroup) name = models.CharField(max_length=255) class Item(models.Model): colors = models.ManyToManyField(Color) For my project, I need to add/remove colors in the admin panel for my items. Currently I have to add them one by one. But in many occasion I want to set all the colors from a ColorGroup at once (and maybe select other colors also). Example: I want my item to be orange, yellow and all colors of group blue (including teal, navy blue etc.) Is there a way to display both colors and group of colors in the ManyToMany list, and if I select a Group it auto select all the colors of this group ? I checked this question but the smart_select doesn't seems to allow both color and group color selection. Edit: The solution I have in mind for now is to add a field 'color group' in item and let user select the group on another list. Then handle logic in the back end. But I would like to avoid adding complexity and redundancy to the DB -
Need to write some tests for OrderDetailView
Need to write test_order_details method to verify receipt of the order: 1)make sure that the order address is in the response body; 2)make sure that there is a promo code in the response body; 3)make sure that the response context is the same order that was created before the test (compare by primary key). This is model: class Order(models.Model): delivery_address = models.TextField(null=True, blank=True) promocode = models.CharField(max_length=20, null=False, blank=True) created_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.PROTECT) products = models.ManyToManyField(Product, related_name="orders") This is view: class OrderDetailView(DetailView): queryset = ( Order.objects .select_related("user") .prefetch_related("products") ) This is tests.py: from django.contrib.auth.models import User, Permission from django.test import TestCase from django.urls import reverse from .models import Order class OrderDetailViewTestCase(TestCase): @classmethod def setUpClass(cls): cls.user = User.objects.create(username='test', password='qwerty') permission_order = Permission.objects.get(codename='view_order') cls.user.user_permissions.add(permission_order) @classmethod def tearDownClass(cls): cls.user.delete() def setUp(self) -> None: self.client.force_login(self.user) self.order = Order.objects.create( delivery_address='ul Verona, d 13', promocode='SALE_123', user=self.user) def tearDown(self) -> None: self.order.delete() def test_order_details(self): response = self.client.get(reverse( 'shopapp:order_details', kwargs={'pk': self.order.pk}) ) self.assertContains(response, self.order.delivery_address) self.assertContains(response, self.order.promocode) I don't know how to make sure that the response context is the same order that was created before the test (compare by primary key). Can you help me please? -
Redmine returned internal error, check Redmine logs for details (Only from Webserver)
I build a Webinterface for Redmine for a better looking experience. Everything works just fine on the virtual development server from django. But when the application runs on my Webserver (IIS) the Python Redmine API seems to have a problem to establish a connection to Redmine. Redmine is installed on the same Server with the help of the Bitnami Redmine Stack. server = Redmine('http://10.0.121.245:81/redmine/', username='user', password="password") server.issue.create( ..... ) This code for the Python Redmine API works just fine on my virtual Server when building the Application, but when published on the Webserver the connection seems to be failing. The Redmine Logs do not show this error. For me it seems to be a problem with the url. Also tried with localhost, but still the same problem. Any idea why this is happening ? -
How to make a default value in ForeignKey using User
I was going through "Django for Beginners", there is a project that make posts with title, author and body fields, u can add posts via admin where in author field u choose either -- or the admin itself, what I'd like to do is if this field is not edited then then its value would be a string that i can pass (i. e. in that case 'anon') . I've found a way to make a default for ForeignKey but without models.User so how to do it in that case? from django.db import models from django.urls import reverse def anon(): return 'User.username="Anon"' class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( "auth.User", on_delete=models.CASCADE, default=anon ) body = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse("post_detail", kwargs={"pk": self.pk}) Firstly I've tried to plainly type in author = models.ForeignKey("auth.User", on_delete=models.CASCADE, default='anon'). Then to make a function that would return the desired string, then looked up models.User fields and found username field, tried to return it in anon() but only got SyntaxError: expression cannot contain assignment, perhaps you meant "=="? when entered makemigrations command -
How to merge two JSONField fields
Postgres allows merging/concatenating two JSONB fields into one. Quoting the relevant Postgres docs: jsonb || jsonb → jsonb - Concatenates two jsonb values. As far as I can see, the Django ORM does not provide an operator for this type of concatenation. django.db.models.expressions.Combinable does not have a || operator. django.contrib.postgres.search.SearchQueryCombinable has a || operator, but this class does not seem to apply here.