Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems with booking site. Cannot remove taken hours
I started building my first website with Django. Trying to create website for my girlfriend`s bussines(manicure salon), and have some problems. First problem was booking form, and picking free hours. Managed to find solution with 2 models and OneToOne relation: class FreeHoursModel(models.Model): EARLY = '10:00' MID = '13:00' LATE = '16:00' HOURS = [(x, x) for x in (EARLY, MID, LATE)] time = models.CharField( max_length=20, choices=HOURS, default=1, ) date = models.DateField( ) def __str__(self): return f"{str(self.date)} - {self.time}" class Customer(models.Model): MAX_LENGTH = 25 name = models.CharField( max_length=MAX_LENGTH, ) last_name = models.CharField( max_length=MAX_LENGTH, ) phone_number = models.IntegerField() date_of_booking = models.DateField( auto_now_add=True ) hours = models.OneToOneField( FreeHoursModel, on_delete=models.DO_NOTHING ) class Meta: get_latest_by = 'date_of_booking' Second problem is how to remove taken hours. These are my views: class IndexView(generic.TemplateView): template_name = 'landing_page/landing_page.html' class BookingView(generic.CreateView): template_name = 'booking_page/booking.html' success_url = reverse_lazy('summary') form_class = CustomerForm def form_valid(self, form): name = form.cleaned_data['name'] last_name = form.cleaned_data['last_name'] phone_number = form.cleaned_data['phone_number'] hour = str(form.cleaned_data['hours']) # print(hour.encode("utf-8")) return super(BookingView, self).form_valid(form) def get_success_url(self): if self.success_url: return self.success_url return super().get_success_url() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['customer'] = CustomerForm() return context class SummaryView(generic.TemplateView): template_name = 'booking_page/summary.html' # if Customer.objects.all(): # latest_created_booking = Customer.objects.latest() # latest_taken_hour_id = latest_created_booking.hours_id # latest_taken_hour = FreeHoursModel.objects.filter(id=latest_taken_hour_id)[0] # … -
I am trying to delete a comment with dynamic success url in my Django Project but it gives me a 404
So The code for this view is My Models, Urls and everything is fine and I event went to check for the data I am requesting manually and funny enough it appeared there. Can someone tell me what mistake is there? class CommentDeleteView(OwnerDeleteView): model = Comment template_name = "ads/comment_delete.html" # https://stackoverflow.com/questions/26290415/deleteview-with-a-dynamic-success-url-dependent-on-id def get_success_url(self): ad = self.object.ad ctx={'ad':ad.id} return reverse_lazy('ads:ad_detail', ctx) -
Where are dokku persistent storage files actually stored on a Mac host machine?
Where are dokku persistent storage files actually stored on a host machine? The documentation says the location is /var/lib/dokku/data/storage/ - but that directory doesn't even exist on my macos m2 host machine - not even /var/lib/dokku/ exists. Docker is installed via Docker Desktop. Whilst I can successfully map a container directory to dokku persistent storage location: dokku storage:ensure-directory myapp dokku storage:mount myapp /var/lib/dokku/data/storage/myapp:/code/media dokku ps:restart myapp and writing files to /code/media/ works, and the files are persisted, and /code/media/ is shown to be a mount point to the host's /var/lib/dokku/data/storage/myapp dir in Docker Desktop's view of the container - when I actually look at that host location, it doesn't exist! e.g. ls /var/lib/dokku/data/storage/myapp No such file or directory Despite this, the solution works and files written to the /code/media directory persist between container re-creations, so they must be kept somewhere. I can't see any related volumes. The only clue is that /var/lib/dokku/data/storage/myapp exists inside the myapp container, albeit with no files in it. Note, my dokku app myapp is a Django app deployed via a Dockerfile (since buildpacks don't work on ARM). -
How to list multiple model records ordered by date in one list
I'm working on ordering system, where a client can request different orders (transfer, shipping, contract, etc.) each of these orders are in different models. I want to implement a page for all client requests, this list should be a combination from Transfer, Shipping, Contract models, and I want to order them by date. Since I have records from different models, then I believe using Django ListView is not an option in this case since ListView requires specifying one model and in my scenario I need three models or even more. I would like to know what is the best way of achieving this in a very effective way?. NOTE: I don't want to combine all of these models into one models, as all of them have different requirements and procedures. I'm thinking of creating a TemplateView and call a function in the get_context_data() which calls all the models, chain the, then order them using lambda function. BUT, I think this approach is not recommended when I have a filtration fields (client ID, Request Date, Request Type, Request Status, etc.) in the same page to filter the list, where having these form fields would require calling the function each time and … -
Is there any alternative way of Q object?
Anyone can tell me, have any alternative way of doing it? I actually searched for a more optimized way than it. def get_queryset(self): return self.queryset.filter(Q(email="") | Q(phone="")).order_by("name") phone and email fields are: phone = models.CharField(max_length=20, blank=True) email = models.EmailField(blank=True) -
Vue.js <template> returns Uncaught SyntaxError: Unexpected token '<' when loaded in Django html files
Good day everyone. I am very new in using both django and vue.js . I am currently creating a project where I use django mainly for backend and integrate vue.js for the frontend. However, I find myself struggling so much on how to call vue.js functionalities or components in django html templates. I just couldn't crack the right steps to correctly call vue in my django project. I don't know either if I am heading the right way or maybe you can help me show the right way to do it. I already installed node.js also. Here are my codes. Django Template at users\templates\users\master.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Profile</title> {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} </head> <body> <div class="container"> {% block content %} {% endblock %} </div> </body> <script src="{% static 'js/vue.global.js' %}"></script> <script src="{% static 'js/custom-vue.js' %}"></script> <script src="{% static 'js/EventForm.vue' %}"></script> Path: C:\Users\Jun\python-project\calendarproject\static\js EventForm.vue <!-- EventForm.vue --> <template> <div class="event-form"> <!-- Your calendar event form HTML here --> <form @submit.prevent="addEvent"> <!-- Form fields for event details --> <!-- For example: Event title, date, time, description, etc. --> <!-- You can use Bootstrap or any other CSS … -
Django: Creating a custom_filter.py that will calculate total duty hours
Newbie here. Thank you in advance. I am working on a Daily Time Record(DTR) with total duty hours calculation per day and display the time-in and time-out (AM) and time-in and time-out (PM). I can already display the time-in and time-out and display the total duty hours if all of the time-in and time-out happened in the same day, but my problem is, when the time-in and time-out span across multiple day such as: # If the attendance happened on the same day, I can compute the total duty hours, in this case, it is 8 hours (hours only) [datetime.datetime(1900, 1, 1, 7, 51, 57), datetime.datetime(1900, 1, 1, 12, 0, 18), datetime.datetime(1900, 1, 1, 12, 19, 24), datetime.datetime(1900, 1, 1, 17, 0, 8)] # But, if the time-in and time-out was on separate day, I was not able to compute the total duty hours. [datetime.datetime(1900, 1, 1, 7, 57, 30)] # Time-in [datetime.datetime(1900, 1, 1, 6, 5, 36)] # Time-out # My initial plan to compute this, is to add an "end_time" and "start_time". # Initially, I want the data to be like this. # With this, I can compute each day by adding an "end_time" and "start_time" # It … -
MS AD login after a long period of being idle - Failed to match request state with session state
I had my work laptop switched off for 3 days and today when I brought it back on and ran PyCharm and went to localhost:8000 in the browser and signed in using Microsoft AD, I got : http://localhost:8000/auth/redirect?code=0.xxx# AuthSecurityError at /auth/redirect Failed to match request state with session state Request Method: GET Request URL: http://localhost:8000/auth/redirect?code=0.xxxm&state=xxxx-xxxx-xxxx-xxxx-xxxx&session_state=xxxx-xxxx-xxxx-xxxx-xxxx Django Version: 4.2.5 Exception Type: AuthSecurityError Exception Value: Failed to match request state with session state Exception Location: D:\workspace\django\projectX\env\lib\site-packages\ms_identity_web\__init__.py, line 259, in _verify_state Raised during: ms_identity_web.django.msal_views_and_urls.aad_redirect Python Executable: D:\workspace\django\projectX\env\Scripts\python.exe Python Version: 3.10.10 I don't know how all of a sudden this is happening because no code was changed in those 3 days. I even cleared cache and cookie data for the last 7 days and still in vain. Same thing happening in another browser. -
Admin user is the same django user - how to solve this
When I built my e-commerce page, I noticed that if I am logged in with user 1, when I log in with user 2 no admin, my django page is automatically logged in with user 2. I don't want this to happen. I want to continue with user 1 on the django site even if logged in with user 2 in the admin. How could this be resolved? Can someone help me please? In my views.py: def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("store:index") elif not form.is_valid() and form.cleaned_data.get('username')!=None or form.cleaned_data.get('password')!=None: messages.error(request,"Invalid username or password.") elif form.cleaned_data.get('username')==None and form.cleaned_data.get('password')==None: messages.error(request,"Please, enter your username and password.") form = AuthenticationForm() return render(request=request, template_name="login//login.html", context={"login_form":form}) -
I have built a django app tocreate a waiting list for artisans but the registration information being entered is not being passed to the database
registration information is not going into the database I tried everything possible and it is not still working. and every other thing works perfectly and I can only add artisans information through the admin panel. Please help -
how to store other model fields in a model field in django
hi i reacently learnd django and i don't have much experience with it and i ran into a problem this is my main model class food(models.Model): name = models.CharField(max_length= 255) category = models.ForeignKey('resturant.category', models.DO_NOTHING, db_column='category') picture = models.ImageField(upload_to='/images/', default=None) rank = models.IntegerField() price = models.BigIntegerField() ingredients = models.ManyToManyField(storage) discription = models.TextField() def __str__(self) -> str : return f'{self.id} - {self.name}' and this is another model in another app class storage(models.Model): name = models.CharField(primary_key=True,max_length=255) count = models.IntegerField() type = models.CharField(max_length=255,null=True) def __str__(self) -> str : return f'{self.name}' and i want to store all the fields in storage model inside the food.ingredients field somthing like an array of objects it should be right now when i make the api of get_all_food on food model it will return [ { "name": "food_name1", "category": 2, "picture": "/images/IMAG0030.jpg", "rank": 12, "price": 450001, "ingredients": [ "rice", "onien", "vegi", "salt", "tomato", "meat", "lemon" ], "discription": "gsdgsgfsfg" }, { "name": "food_name2", "category": 3, "picture": "/mehrbanoo/images/IMAG0075.jpg", "rank": 28, "price": 50000, "ingredients": [ "rice", "vegi", "beans", "lemon" ], "discription": "ssdafafadsada" } ] but i need it to be like : [ { "name": "food_name2", "category": 3, "picture": "/mehrbanoo/images/IMAG0075.jpg", "rank": 28, "price": 50000, "ingredients": [ { "rice",2,gr } { "vegi",3,gr } … -
Django count() with a prefetch_related query seems not to work
I am working in a Django project and I could not get to work the count() function with Prefetch. I have 20 orders but only 17 has its payout='available'. If I try to get the count() after filter inside a Prefetch Query: order = Order.objects.filter(vendors__in=[vendor.id], is_ordered= True).order_by('-created_at') promise_ordered_products_orders = order.prefetch_related( Prefetch( 'orderedproductorders', queryset = OrderedProduct.objects.filter(product__vendor__id=vendor.id, payout='available') ) ) print(promise_ordered_products_orders.count()) I get 20 orders as the count() function result i.e all orders. But it should be only 17. I already manage to solve it with for loop to a list =[] and len(). I was wondering if there is anyway to get count() to work inside for the 'orderedproductordes' and not for all orders in the Prefetch Query. -
Dynamic, client-side update of drop down choices in Django admin?
My goal is to update the Pianos pane below with pianos belonging to the dynamically chosen Customer. The Piano panes are rendered by Django Admin's filter_horizontal option. I thought it might be simpler and more lightweight to use Javascript rather than django-autocomplete-lite. I found some excellent code which interfaces with SelectBox.js (SelectBox is used by Django) which I can use to update the Pianos pane. My adaptation of it is called "updatePianoList()" below. The remaining piece is to query the server for a list of pianos based on the Customer chosen. I wrote an Ajax function triggered by change events on the Customer pane. However, I'm finding apparent conflicts (symptoms below) with multiple other events registered on the parents of the "Customer" pane. The events expanded below are all Django's attached to a parent with the exception of the one indicated by red arrows. Here's the relevant JS in the Django template: function updatePianoList() { alert("Step 1: Updating piano list"); django.jQuery.ajax({ // FIXME: hardwired url for testing url: "http://localhost:8000/giraffe/customersPianos/3", type: 'GET', dataType: 'text/plain' }) .done (function(response, textStatus, jqXHR) { console.log(response.responseText); updateOptionsDisplay(); }) .fail (function(response, textStatus, errorThrown) { console.log("ReadyState: "+response.readyState+"\nstatus: "+response.status); console.log("ResponseText: "+response.responseText); }); } function detectCustomerDropdownChange() { document.getElementById('select2-id_customer-container').addEventListener('change', updatePianoList); } … -
WIX API-Query-filter for date-created suddenly returns 500 Response
Context: WIX-API https://dev.wix.com/docs/rest/articles/getting-started/api-query-language I am using the following query, to get all orders that are beyond the defined date. (Using Python in context of Django-Framework) I used this query a lot of times and suddenly it failed. data = { "query": { "filter": "{\"dateCreated\": {\"$gte\": \"" + start_date + "\"}", "paging": { "limit": 100, "offset": counter, }, "sort": "[{\"dateCreated\": \"desc\"}]" } } When i delete the filter-options, the query works, so apparently, the mistake must be within the filter-option. I couldn't find any recent release notes from WIX-Documentation that may have had an effect on my query. I also tried a depressing amount of different variations for the query, but nothing helped. Additional context: start_date = "2023-01-01T00:00:01.222Z" url = 'https://www.wixapis.com/stores/v2/orders/query' headers = { 'Content-Type': 'application/json', 'Accept': 'application/json, text/plain, */*', 'Authorization': api_key, 'wix-site-id': site_id } Of course: i checked site-id and the api-key if there are any mistakes Posting the request: response = requests.post(url, headers=headers, json=data) The answer is always <Response [500]>. -
How to access instances of models in view in order to save both forms at once
I am trying to combine Two models into one form. However I cannot save the form as it is not an instance of the models. What I'm after is a way to access the models as instances and then save. I am using crispy forms, I have described what I have tried at the bottom of the post, I have no idea why this is not working so as always any help is appreciated. This is my model.py file: from django.db import models # Create your models here. BOOKING_STATUS = ((0, 'To be confirmed'), (1, 'Confirmed'), (2, 'Declined')) class Customer(models.Model): first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) email = models.EmailField() phone_number = models.CharField(max_length=20) def __str__(self): return f"Customer {self.first_name + ' ' + self.last_name}" class Booking(models.Model): booking_date = models.DateField() booking_time = models.TimeField() number_attending = models.IntegerField(default=2) booking_status = models.IntegerField(choices=BOOKING_STATUS, default=0) customer = models.ForeignKey('Customer', on_delete=models.CASCADE) def __str__(self): return f"Booking by {self.customer}" forms.py: from .models import Customer, Booking from django import forms class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = '__all__' class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ('booking_date', 'booking_time', 'number_attending') class CustomerBookingForm(forms.Form): customer_form = CustomerForm() booking_form = BookingForm() and my view.py from django.shortcuts import render from .forms import CustomerBookingForm # Create … -
Django Formsets for Creating Multiple Related Model Instances
I have a Ticket model. I've created a Ticket form relating to this model. There is a button to add new forms, so you can create multiple instances of the Ticket model from the same web page. This is managed with a formset. There is also another form (referred to as form2), which allows you to create instances of the TicketAsset form. You should be able to add multiple instances of this form, for each instance of the Ticket form (managed with formset2). For example: if we have two instances of the Ticket Form, it would be possible to add, say, two instances of the TicketAsset Form, which relate to the Ticket instance created in the first instance of the Ticket Form. When we add the second instance of the Ticket form, this should have with it a new instance of the TicketAsset form, as well as another button to add more instances of the TicketAsset form (which all relate to the second instance of the Ticket Form). In this case say we create three instances of the TicketAsset form. Upon submission of the form, the expected outcome would be: Two instances of the Ticket model are created and saved … -
ValueError: 'AccessPolicy' instance needs to have a primary key value before this relationship can be used
I'm upgrading the legacy project from Django 2.2 to Django 4.2. Everything works fine except the model, where ManyToMany field is used. The model: # models.py class AccessPolicy(TimeStampedModel): name = models.CharField(max_length=255, null=False, blank=False) external_id = models.CharField(max_length=255, unique=True, null=True) version_hash = models.CharField(max_length=255, null=False, blank=False) read_only = models.BooleanField(default=False, help_text=('Some text')) users = models.ManyToManyField(User, blank=True) class Meta: verbose_name = 'Access Policy' verbose_name_plural = 'Access Policies' def __str__(self): return f'{self._meta.object_name} Object ({self.pk})' The form: # forms.py class AccessPolicyForm(forms.ModelForm): external_id = forms.CharField(disabled=True, required=False) rules = forms.CharField(widget=QueryBuilderWidget) class Meta: model = AccessPolicy fields = 'name', 'external_id', 'read_only', 'rules', 'users', def clean_external_id(self): external_id = self.cleaned_data.get('external_id') if not external_id: return md5(f"{str(self.instance.created)} {self.cleaned_data.get('name')} {self.data.get('rules')}") return external_id def clean_rules(self) -> CleanedRules: raw_rules: RawRules = json.loads(self.cleaned_data.get('rules')) conditional_serializer = RulesSerializer(data=raw_rules) if not conditional_serializer.is_valid(): raise ValidationError(conditional_serializer.errors) return conditional_serializer.validated_data def save(self, commit=True): self.instance.version_hash = hash_dict(self.cleaned_data.get('rules')) return super().save(commit) def _save_m2m(self): self.instance.rules.all().delete() self._save_condition() self._save_users() def _save_users(self): self.instance.users.clear() self.instance.users.add(*self.cleaned_data.get('users')) def _save_condition(self): root_condition = RulesSerializer().create(self.cleaned_data.get('rules')) root_condition.access_policy = self.instance root_condition.save() The admin file: # admin.py class AccessPolicyAdmin(admin.ModelAdmin): form = AccessPolicyForm list_display = 'name', search_fields = 'name', formfield_overrides = { models.ManyToManyField: { 'widget': FilteredSelectMultiple(attrs={'size': 20}, verbose_name='linked users', is_stacked=False) }, } def get_form(self, request, obj: AccessPolicy = None, change=False, **kwargs): form = super().get_form(request, obj, change, **kwargs) data = self._get_form_data(obj or AccessPolicy()) … -
is possible deploy a Django project with a App instead a Droplet in DigitalOcean?
I need to deploy a Django application, but I only find tutorials using droplets on DigitalOcean, I would like to know if it is possible to deploy it through an App I followed the instructions from this repository, https://github.com/codingforentrepreneurs/Try-Django-3.2, but it didn't work for me -
Django-- Multiple Models with Multiple Databases
I am working on file transformation workflows and the whole project is based on Django. How the project works is , each django app is a new workflow , and once a files comes in it will invoke the workflows one after the another. My question is how to connect multiple databases from single model.py. Below is what I am trying to achieve The Main Project Structure Kappa |--Kappa |--FileTransformSAP |--FileTransformARIBA |--FileTransformWorkday ..... ..... Each of the Apps have a similar Structure listed below. FileTransformSAP |--__init__.py |--admin.py |--apps.py |--models.py |--tests.py |--views.py I have three Databases Namely, Landing, Staging and Final What I am trying to achieve is the model.py file will have three different classes namely, _landing, _staging and _final and this three classes should be able to interact with three different databases and mentioned above. I am already using routers.py to segregate databases for auth and application, but I am getting stuck when single model.py containing various model class needs to be applied to different databases Sample Model.py class <anything>_landing(models.Model): definition class Meta: app_label = '<anything>_landing' class <anything>_staging(models.Model): definition class Meta: app_label = '<anything>_staging' class <anything>_final(models.Model): definition class Meta: app_label = '<anything>_final' Along with this created the following routes.py … -
django restframework sorting
models.py class Entity(BaseFields): entity_name_en = models.CharField(max_length=250) category = models.ForeignKey(Category, on_delete=models.CASCADE,null=True,blank=True) class EntityRelation(models.Model): name = models.CharField(max_length=250) class EntityRelationship(models.Model): entity = models.ForeignKey(Entity, on_delete=models.CASCADE, related_name="entity") relation = models.ForeignKey(EntityRelation,on_delete=models.CASCADE) related_entity = models.ForeignKey(Entity, on_delete=models.CASCADE, related_name="related_entity") EntityRelation contains "Parent" and "Child" serializers.py class EntityListserializer(ModelSerializer): parent = SerializerMethodField(read_only=True) def get_parent(self, obj): relation_obj = EntityRelationship.objects.filter(entity=obj,relation__name="Parent").first() if relation_obj: return {"id":relation_obj.id,"related_entity":{"id":relation_obj.related_entity.id,"name":relation_obj.related_entity.entity_name_en}} class Meta: model = Entity fields = ("id","category","parent") views.py class EnityListView(ListAPIView): permission_classes = [AllowAny,] serializer_class = EntityListserializer def get_queryset(self, *args, **kwargs): sort = json.loads(self.request.GET.get("sort")) parnt = sort.get("parent") queryset_list = Entity.objects.all().order_by("-created_date") if parnt: if parnt == 'asc': queryset_list = queryset_list.order_by(F("related_entity").asc(nulls_last=True)) if parnt == 'desc': queryset_list = queryset_list.order_by("-related_entity") return queryset_list does anyone know how to sort queryset_list with parent field {"id": 1,"category":1,"parent":{"id": 1,"related_entity": {"id": 1,"name": "entity 1"}}} -
Database updates are sometimes working, and sometimes not (Django & Flutter)
I am using the Django Rest Framework to build an API which connects a Flutter app to a MySQL database. I am using PythonAnywhere to host my code, and have the lower tier paid plan. I have two Models: User (which inherits from AbstractUser) and Client. They both have a JsonField named "counters" which follow this key,value structure: {String (an identifier): int (a counter)} I have a view like that looks something like this: class UpdateCounters(APIView): permission_classes = [AllowAny] def post(self, request): username = request.data.get("username") identifier = request.data.get("identifier") user = User.objects.get(username=username) client = Client.objects.get(user_id=user) updates = {} try: with transaction.atomic(): counters = user.counters counters[identifier] = counters.get(identifier, 0) + 1 user.counters = counters updates["user"] = user countersC = client.counters countersC[identifier] = countersC.get(identifier, 0) + 1 client.counters = countersC updates["client"] = client for obj in updates.values(): obj.save() return JsonResponse({'success': True}, status=status.HTTP_200_OK) except IntegrityError as e: return JsonResponse({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: return JsonResponse({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) The thing is, when this call is made, the User object goes through all the desired changes, whereas the Client object, SOMETIMES (approx. 50% of the time), does not. I have tried using the update_fields parameter of the .save() method, but this only made the … -
535330#535330: conflicting server name "www.aniconnect.org" on 0.0.0.0:80, ignored
I have made a django chatting application that uses websockets (django-channels) to implement its chatting functionality. I have used nginx and gunicorn for production for this website. The following is the nginx config file: server { listen 80; server_name www.aniconnect.org; ssl_certificate /etc/letsencrypt/live/www.aniconnect.org/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/www.aniconnect.org/privkey.pem; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/gamedeveloper/anime_chat/anime_chat_app/static/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /ws/ { proxy_pass http://unix:/run/gunicorn.sock; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } The following are the ports I use on this site: gamedeveloper@animechatapp:~$ sudo ufw status Status: active To Action From -- ------ ---- 22/tcp ALLOW Anywhere 80/tcp ALLOW Anywhere 8001/tcp ALLOW Anywhere 443/tcp ALLOW Anywhere 22/tcp (v6) ALLOW Anywhere (v6) 80/tcp (v6) ALLOW Anywhere (v6) 8001/tcp (v6) ALLOW Anywhere (v6) 443/tcp (v6) ALLOW Anywhere (v6) The following is settings.py: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY ='django-insecure-00ejr3$lw40)nu8ojp70w29ju(c+jgol94_m3-otie-csmt^@t' # SECURITY WARNING: don't run with debug turned on … -
Django Page not found (404) - DetailView with Primary Key [closed]
Bonjour, Je butte depuis quelques jours sur ce problème et je ne vois pas ou est-ce que je me trompé. Je veux afficher une vue detail (DetailView) d'un client ou article. Et j'ai toujours cette erreur: "" Request URL: http://127.0.0.1:8000/papis/viewcustomer/7/' "" Quand j'enlève le "" ' "" juste après le pk, la page s'affiche. "" Request URL: http://127.0.0.1:8000/papis/viewcustomer/7/ "". Voici mon extrait de code. D'avance je vous remercie **urls.py** `app_name = "nrn" urlpatterns = [ path('contact/', signup, name="contact"), # Customer path('', HomeViewCustomer.as_view(), name="home"), path('addcustomer/', AddViewCustomer.as_view(), name="create-customer"), path('viewcustomer/<int:pk>/', DetailViewCustomer.as_view(), name="view-customer"), path('editcustomer/<int:pk>/', EditViewCustomer.as_view(), name="edit-customer"), path('deletecustomer/<int:pk>/', DeleteViewCustomer.as_view(), name="delete-customer"), ` **models.py** `customer_name = models.CharField(max_length=255, unique=True, verbose_name="Nom du Client") gerant = models.CharField(max_length=255, blank=True,null=True, verbose_name="Nom du dirigeant ou son représentant") siret = models.CharField(max_length=100, default="non renseigné", verbose_name= "Numéro siret") def get_absolute_url(self): return reverse("nrn:home") ` **views.py** `from django.views.generic import CreateView, UpdateView, DeleteView, ListView, DetailView from papis_app.models import Customer class DetailViewCustomer(DetailView): """ Vue info/détail d'un client """ model = Customer template_name = "client/detail_client.html" context_object_name = "custome" ` **detail_client.html** `{% block content %} <hr> <div id="client"> <h3> Nom du client: {{ custome.customer_name }} </h3> <h3>Contact: </h3> <div> <ul> <li>{{ custome.gerant }} </li> <li>{{ custome.siret }} </li> </ul> </div> </div> {% endblock %}` -
Django - Custom save method not being applied in loop
I have this model: class AccountingRevenue (models.Model): class AccountingRevenueStatus (models.TextChoices): TORECEIVE = 'A RECEBER', 'A RECEBER' PARTIAL = 'RECEBIDO PARCIAL', 'RECEBIDO PARCIAL' FULL = 'RECEBIDO TOTAL', 'RECEBIDO TOTAL' objects = models.Manager() accpresentation = AccountingRevenueManager() branch = models.ForeignKey(Branchs, on_delete=models.PROTECT) sale_date = models.DateField(blank=True, null=True) accountplan = models.ForeignKey(AccountsPlan, on_delete=models.PROTECT) customer = models.ForeignKey(Customers, on_delete=models.PROTECT, null=True, blank=True) amount_to_receive = models.DecimalField( max_digits=14, decimal_places=2, ) due_date = models.DateField() amount = models.DecimalField( max_digits=14, decimal_places=2, ) status = models.CharField( max_length=16, choices=AccountingRevenueStatus.choices, ) accnotes = models.CharField( max_length=1000, blank=True, null=True, unique=False, error_messages={ 'max_length': 'A observação pode ter 1000 caracteres no máximo.', } ) tax = models.DecimalField( max_digits=5, decimal_places=2, blank=True, null=True, ) term = models.PositiveIntegerField( blank=True, null=True, ) receive_in = models.DateField( blank=True, null=True, ) taxed_amount = models.DecimalField( max_digits=14, decimal_places=2, blank=True, null=True, ) total_taxes = models.DecimalField( max_digits=14, decimal_places=2, blank=True, null=True, ) class Meta: verbose_name_plural = 'AccountingRevenue' def save(self, *args, **kwargs): cards = Cards.objects.all() if 'CARTÃO' in str(self.accountplan): if cards: for item in cards: if self.accountplan_id == item.accountplan_id: self.tax = item.card_tax self.term = item.payment_term self.total_taxes = round(Decimal(self.amount_to_receive * (self.tax / 100)), 2) self.taxed_amount = round(Decimal(self.amount_to_receive - self.total_taxes), 2) self.receive_in = self.sale_date + relativedelta(days=self.term) else: self.tax = 0 self.term = 0 self.total_taxes = 0 self.taxed_amount = self.amount_to_receive self.receive_in = self.sale_date else: self.tax = 0 self.term … -
Reverse accessor clash between Django's auto generated fields
I have a base table that I want to extend in a couple different apps installed in my project. My issue is that I usually want the table to be named the same thing despite what app it is installed in. These apps all live in the same PostGres database, in separate schemas: #App1 ParentModel(models.Model): #fields #App2 ChildModel(ParentModel): #fields #App3 ChildModel(ParentModel): #fields When I try to run makemigrations, it complains about a reverse accessor clash between the auto generated 'childmodel_ptr' fields. It suggests adding a 'related_name' argument. However obviously I cannot do that as this field is being auto generated by Django. Is there a mechanism by which I can supply a 'related_name' argument to whatever django machinery is generating that field?