Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
main.models.Flashcard.DoesNotExist: Flashcard matching query does not exist. Even though it does
def deleteCard(request): user = request.user print(request.POST) if request.method == "POST": header = request.POST.get("header") question = request.POST.get("question") answer = request.POST.get("answer") print(header, question) subject = Internal_Subject.objects.get(name="Economics") set = Flashcard_set.objects.get(subject=subject, name="Topic 1") try: flashcard = Flashcard.objects.get(set=set, header=header, question=question, answer=answer) flashcard.delete() print("delete was successful") except Flashcard.DoesNotExist: print("this is not working") flashcardView(request) The object does exist, I've seen it in the admin panel, the parameters are the exact same as the ones used for querying. When I refresh the page the card is still there. There are no duplicates of this model. I've tried filter().first that said nonetype object does not have property delete(), even though the card does exist. Please help I really don't know what I'm doing wrong here. -
Django form doesn't take request.POST values
I have a problem with my project. When i click on the submit button of the form i can see the correct data in request.POST (debug mode), but the function "form.is_valid" return an error. Infact if i skip the function e write only form.save it will raise "NOT NULL constraint failed: fatture_viaggio.distanza_km". Here is my code: def clienti(request): clienti_list = Cliente.objects.all().order_by('nome').exclude(nome='Inalca') viaggi_list = Viaggio.objects.all().order_by('-data_viaggio') if request.method == 'POST': if 'Aggiungi_Cliente' in request.POST: formC = ClienteForm(request.POST) if formC.is_valid(): nuovo_cliente = formC.save() return redirect('clienti') formV = ViaggioForm(request.POST) #if formV.is_valid(): nuovo_viaggio = formV.save() return redirect('clienti') else: formC = ClienteForm() formV = ViaggioForm() return render(request, 'fatture/clienti.html', {'formC': formC, 'formV': formV, 'clienti': clienti_list, 'viaggi': viaggi_list}) The FormC works fine, only the formV has this problem. -
Cannot issue ssl certificate via acm companion from dockerfile
I have a site that should be launched from docker and obtain an SSL certificate for itself, and at the time of launch I receive the following error: nginx-proxy-acme | [Wed Dec 13 17:50:52 UTC 2023] Using CA: https://acme-v02.api.letsencrypt.org/directory nginx-proxy-acme | [Wed Dec 13 17:50:52 UTC 2023] Creating domain key nginx-proxy-acme | [Wed Dec 13 17:50:53 UTC 2023] The domain key is here: /etc/acme.sh/default/admin.innodih.com.ua/admin.innodih.com.ua.key nginx-proxy-acme | [Wed Dec 13 17:50:53 UTC 2023] Single domain='admin.innodih.com.ua' nginx-proxy-acme | [Wed Dec 13 17:50:53 UTC 2023] Getting domain auth token for each domain nginx-proxy-acme | [Wed Dec 13 17:50:55 UTC 2023] Getting webroot for domain='admin.innodih.com.ua' nginx-proxy-acme | [Wed Dec 13 17:50:55 UTC 2023] Verifying: admin.innodih.com.ua nginx-proxy-acme | [Wed Dec 13 17:50:59 UTC 2023] admin.innodih.com.ua:Verify error:185.69.153.243: Fetching http://admin.innodih.com.ua/.well-known/acme-challenge/ietg6hf8EmIOhAh2Z7AJHdrcprTem64hYqxqRlcqOlk: Connection refused nginx-proxy-acme | [Wed Dec 13 17:50:59 UTC 2023] Please check log file for more details: /dev/null nginx-proxy-acme | Sleep for 3600s I've been looking through a lot of problems and couldn't find a specific solution for me, sticking my docker compose: version: "2" services: db: image: postgres:15 container_name: db volumes: - ~/.pg/pg_data/ic:/var/lib/postgresql/data env_file: - .env ports: - "127.0.0.1:15432:5432" web: image: web:latest container_name: web depends_on: - db volumes: - static_volume:/ic/static - media_volume:/ic/media env_file: - .env environment: … -
How to make django file changes that can reflect it on the main server
I have made a change in the django default auth model template. I have added a new column in existing default auth table. So from my project's models.py, I have made change in the django auth model which is present in django.contrib.auth.modela.py So now the changes are stored in migrations file which is present in my local file as comtrib.auth/migration folder is present locally. Now the problem is it is reflecting correctly on my local pc once make migrations and migrate cmds are executed, but when I want to export the code, ofcourse this migration file will not be pushed, and the main server does not run this 2 cmds as it reads it automatically from migration files to avoid any future loss so how do I put it on the main server so that it can be implemented and people can start seeing the change. Thank You 🙌🏻 The only thing is server does not run any cmds like makemigrations and migrate and also manually storing file at particular location doesn't help either. -
IndexError while performing Subqueries on django
I have a post list for which I am trying to retrieve some data from its related models, to display in a post list. The data I need is the latest comment made, the user, the user group and the date and text of the comment. I am trying to achieve this result with this complex annotate query: all_posts=Post.objects.all() posts = all_posts.annotate( comment_count=Count('comment'), g_origin=Coalesce(Subquery( PostGroup.objects.filter(post=OuterRef('pk')).values('group') ), Value(0)), latest_comment_author=Coalesce(Subquery( PostComment.objects.filter(post=OuterRef('pk')).values('user__user') ), Value(''), latest_comment_created=Coalesce(Subquery( PostComment.objects.filter(post=OuterRef('pk')).order_by('-created').values('created') ), Value('')), latest_comment_text=Coalesce(Subquery( PostComment.objects.filter(post=OuterRef('pk')).order_by('-created').values('text') ), Value('')) ) But this is just resulting in IndexError: list index out of range, but looks like the error is being originated within Django's internal files. Some posts could have no comments, no user or no data, but I used to think I could solve that with Coalesce(x, default_value, but it's still giving the error) I also tried to reduce it to just all_posts=Post.objects.all() posts = all_posts.annotate( comment_count=Count('comment') ) or to all_posts=Post.objects.all() posts = all_posts.annotate( g_origin=Coalesce(Subquery( PostGroup.objects.filter(post=OuterRef('pk')).values('group') ), Value(0)), ) But still, it's giving the error. What could the problem be? -
Django time zone issue in my project dash board
I can't get the today_entries,week_entries and month_entries in the following code : class DashBoardView(APIView): def get(self, request): # Count the number of users total_users = User.objects.count() total_workers = User.objects.filter(role='worker').count() total_credits = Decimal(0.00) total_debits = Decimal(0.00) wallet_entries = AdminWallet.objects.all() print("wallet entries",wallet_entries) today = timezone.now() print("today",today) start_of_week = today - timezone.timedelta(days=today.weekday()) print("start_of_week",start_of_week) start_of_month = today.replace(day=1) print("start of the month",start_of_month) start_of_year = today.replace(month=1, day=1) print("start of the year",start_of_year) for entry in wallet_entries: total_credits += entry.credit total_debits += entry.debit total_balance = total_credits - total_debits print("total balance",total_balance) week_entries = wallet_entries.filter(created_at__gte=start_of_week) print("week entries",week_entries) month_entries = wallet_entries.filter(created_at__gte=start_of_month) print("month entries",month_entries) year_entries = wallet_entries.filter(created_at__gte=start_of_year) print("year entries",year_entries) total_revenue_week = sum(entry.credit for entry in week_entries) - sum(entry.debit for entry in week_entries) total_revenue_month = sum(entry.credit for entry in month_entries) - sum(entry.debit for entry in month_entries) total_revenue_year = sum(entry.credit for entry in year_entries) - sum(entry.debit for entry in year_entries) Pending_Bookings = Appointment.objects.filter(status='Pending').count() Accepted_Bookings = Appointment.objects.filter(status='Accepted').count() Cancelled_Bookings = Appointment.objects.filter(status='Cancelled').count() Rejected_Bookings = Appointment.objects.filter(status='Rejected').count() today_entries = wallet_entries.filter(created_at__date=today) print("today entries",today_entries) total_revenue_today = sum(entry.credit - entry.debit for entry in today_entries) seven_days_ago = today - timezone.timedelta(days=7) daily_Bookings_data = [] daily_revenue_data = [] for i in range(7): day_start = seven_days_ago + timezone.timedelta(days=i) day_end = day_start + timezone.timedelta(days=1) Appointments_on_day = Appointment.objects.filter(date1__gte=day_start, date1__lt=day_end).count() revenue_on_day = wallet_entries.filter(created_at__date=day_start).aggregate( total_credit=Sum('credit'), total_debit=Sum('debit') ) print("revenue on day",revenue_on_day) … -
Django display any querry as html table
I want to display a simple query in my database as an HTML table. But i a missing something either in the template or general logic of data management in Django. First i am creating a model like that : class Book(models.Model): title = models.CharField(max_length=128, unique =True) quantity = models.IntegerField(default=1) Then making a view with a context containing both the column's names of the query and the query object such as : def books(request): context = {"rows":Book.objects.all(),"fields" : Book._meta.get_fields()} return render(request,"blog/books.html",context) Finally i am trying to iterate over the value of the query in my template so i can put them in a HTML table: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Our Books</title> </head> <body> <table border="1"> <thead> <tr> {% for field in fields %} <th>{{ field.verbose_name }}</th> {% endfor %} </tr> </thead> <tbody> {% for row in rows %} <tr> {% for field in fields %} <td>{{ row[field] }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> </body> </html> Adding the header of the table works fine but this part is not working : {% for row in rows %} <tr> {% for field in fields %} <td>{{ row[field] }}</td> {% endfor %} </tr> {% endfor %} … -
Django Admin Search - returning duplicates when search_field includes many-to-many
I'm receiving multiple duplicate objects when using Django Admin search. I have two models involved. Organisation and OrgAlias(Organisation Alias). Each Organisation may have multiple aliases and each alias may be attached to multiple Organisations. The models: class OrgAlias(models.Model): name = models.CharField(max_length=255,unique=True) def __str__(self): return self.name class Organisation(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) aliases = models.ManyToManyField(OrgAlias) ... My Django Admin class: class OrganisationAdmin(admin.ModelAdmin): search_fields = ['aliases__name'] ... I've tried overriding the ModelAdmin get_search_results function with various strategies. e.g. def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super().get_search_results(request, queryset, search_term) queryset = queryset.distinct() return queryset, use_distinct The result is always the same. If I have 3 aliases attached to and organisation. The organisation will appear 3 times in the search results. Similar queries work fine in the shell. It's just in django admin the problem appears. Is there a simple fix or workaround for this? -
Why is my Jquery autocomplete not working on my search bar?
I have a search bar that should be visible in all my pages in django, however the autocomplete is not working. my bse.html has the following: <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> this is my search bar: <div class="sbar "> <div class="row-search "> <div class="col-6"> <form action="{% url 'search' %}" method="get"> <div class="input-size input-group mb-3"> <input type="text" name="q" id="searchBox" class="form-control" placeholder="Search..."> <button class="btn btn-primary" type="submit">Search</button> <div id="search-suggestions-dropdown"></div> <!-- Add this line --> </div> </form> </div> </div> </div> this is my script inside my base.html: <script> $(document).ready(function(){ $('#searchBox').autocomplete({ source: function(request, response) { console.log("Making AJAX request with query:", request.term); $.ajax({ url: "{% url 'search' %}", dataType: 'json', data: { 'q': request.term }, success: function(data) { console.log("Received data:", data); var suggestions = []; data.forEach(function(item) { suggestions.push({ label: item.label, value: item.value }); }); response(suggestions); } }); }, minLength: 2, select: function(event, ui) { console.log("Selected item:", ui.item); window.location.href = ui.item.value; } }); }); </script> this is from my views.py: class SearchView(View): def get(self, request, *args, **kwargs): query = request.GET.get('q') print("Received query:", query) # Print the received query if query: infos = Info.objects.filter(Q(firstName__icontains=query) | Q( middleName__icontains=query) | Q(lastName__icontains=query)) files = Files.objects.filter(fileName__icontains=query) results = list(infos.values('firstName', 'middleName', 'lastName', 'orphanID')) + list(files.values('fileName', 'fileID')) results = [ { 'label': … -
Insert the row to the Queryset manually
I have objects and filter, which get the label value pair from database. results = (m.Drawing.objects. annotate(label=F('update_user__name'),value=F('update_user')). values('label','value'). annotate(dcount=Count('update_user__name')). order_by()) print(results) serializer = s.SearchChoiceSerializer(instance=results, many=True) Results is like this,print(results) <SafeDeleteQueryset [{'label': 'admin', 'value': 1, 'dcount': 13}, {'label': 'demouser1', 'value': 2, 'dcount': 13}]> Now, I want to insert this {'label':'myuser', 'value':2,'dcount':23} to SafeDeleteQuerySet manually before sending to the serializer. I it possible? -
Problem with Error 502 in simple django method
I have a strange problem with django. I'm taking my first steps in Python, so maybe this question is stupid - if so, I apologize in advance :) I have 2 methods: def method1(self): url = settings.PAYMENT_GATEWAY_URL + "payments/" + self.bank_account_nr + "/" + settings.PAYMENT_POS_ID + "/function1/" ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE data = urllib.request.holiday(url, context=ctx) contents = data.read().decode('utf-8') # content = '{"amount_sum": "120.00"}' data = json.loads(contents) data = data.get("amount_sum") return data def method2(self): url = settings.PAYMENT_GATEWAY_URL + "payments/" + self.bank_account_nr + "/" + settings.PAYMENT_POS_ID + "/function2/" ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE data = urllib.request.holiday(url, context=ctx) contents = data.read().decode('utf-8') data = json.loads(contents) return data function2 return : {"status": "OK", "paymentsA": 1, "paymentsCt": 1, "paymentsD": 0} function1 return {"amountsum": "120.00"} When calling method 1 - everything works fine, in the case of method 2 the application takes a very long time and throws error 502, Both links load quickly in the browser. Both web addresses are on 1 server and are 1 application -
How to create Django Rest Framework translate mixin?
I'm trying to write a django translate mixin for my project. I configured the settings.py file, created a model, view, serializer and mixin. when I run the application an error occurs: "TranslationFieldMixin.get_field_names() missing 2 required positional arguments: 'declared_fields' and 'info'". This error occurred after I added this code to my serializer: def to_representation(self, instance): language = get_language() self.fields = self.get_field_names(language=language) return super().to_representation(instance) How can I solve this problem? SETTINGS.PY INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'parler', 'rest_framework', 'store', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LANGUAGE_CODE = 'en-us' LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] LANGUAGES = [ ('en', _('English')), ('es', _('Spanish')), ('fr', _('French')), ('ru', _('Russian')), ] TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True MODELS.PY from django.utils.translation import gettext_lazy as _ class Article(models.Model): title = models.CharField(_('title'), max_length=100) content = models.TextField(_('content')) def __str__(self): return self.title VIEWS.PY class ArticleDetailAPIView(RetrieveUpdateDestroyAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer SERIALIZERS.PY class ArticleSerializer(TranslationFieldMixin, serializers.ModelSerializer): class Meta: model = Article fields = ['id', 'title', 'content'] def to_representation(self, instance): language = get_language() self.fields = self.get_field_names(language=language) return super().to_representation(instance) UTILS.PY class TranslationFieldMixin(): def get_field_names(self, declared_fields, info, language=None, *args, **kwargs): field_names = super().get_field_names(declared_fields, info, *args, **kwargs) if language: translated_field_names = [ str(_(field_name)) … -
USE_L10N deprecated, but it disables DATETIME_INPUT_FORMATS when removed
Have I found a bug in Django? The config setting USE_L10N is deprecated since 4.0 and scheduled for removal in 5.0. However, the documentation of forms.DateField for 5.0 still states If no input_formats argument is provided, the default input formats are taken from the active locale format DATE_INPUT_FORMATS key, or from DATE_INPUT_FORMATS if localization is disabled. Which begs the question, how does one disable localisation and enable the DATE_INPUT_FORMATS setting once USE_L10N = False is not longer possible? I don't want to upgrade to 5.0 yet, so I cannot easily test this. I have established that on 4.2, if I comment out the deprecated USE_L10N = False in my settings.py, then DATE_INPUT_FORMATS ceases to be honoured. I wonder whether anybody running Django 5.0 can comment? -
Django API Database Design for both Multi-Tenant and Customer (No-Tenancy) Authentication
I am developing a backend API using Python Django Rest Framework. The frontend will handle authentication at these 3 URL paths: Customer Authentication URL: www.mydomain.com Functionality: Customers can search for and purchase products. To complete a purchase, customers must create an account. This account provides access to view purchase history and the option to save payment methods. Multi-Tenancy Authentication URL with tenant subdomain: myclient.mydomain.com Functionality: Clients can login to manage their accounts and add their products to sell. Additionally, clients need the ability to give their employees their own login to assist in managing their listed products. Internal Admin Authentication URL with admin subdomain: admin.mydomain.com Functionality: Admins can access tools for customer and client support. What would be the best way to design my database schema to handle this in the most efficient way and also keeping my database organized and as clutter free as possible? I am just now starting this part of my project, so I do not have any code written for my schema as of yet. I have done a ton of Googling and YouTubing to find a solution and there isn't a whole lot of info on multi-tenancy architecture around the use case that I … -
Managing migrations while moving from default taggit tags to taggit custom tags
I was working on adding Tags to Articles, Comments using django-taggit. Butnow I need the Tags to be associated with Account - so every tag must be tied to an account_id and only Articles, Comments of that Account can access these tags. To achieve this, I had to implement a CustomTag. In between these two stages, there were few other migrations relavant to other models. Example 0021_add_tags_to_articles_and_comments.py 0022_some_other_model_migration.py 0023_some_other_model_migration.py 0024_use_custom_tag_with_custom_taggedobject.py Taggit documentation mentions the below to remove the tables taggit created and using custom tags But this is messing up with my initial migration that added taggit tables because 0021_add_tags_to_articles_and_comments.py has dependencies class Migration(migrations.Migration): dependencies = [ ( "taggit", "0006_rename_taggeditem_content_type_object_id_taggit_tagg_content_8fc721_idx", ), ("blog_app", "0020_blog"), ] I cant delete all the migrations and redo them because of these changes are being used in current app. Is there any way to achieve this? Apologies if the question doesn't seem well explained. -
How to filter by user or all users in same viewset in Django REST framework
I am a beginner in Django REST Framework and I want to ask how I can (and if at all possible) filter listings by user id or return all listings if user id is not set as a query parameter. Also, each user should be able to edit or delete only their own listings, but be able to see the listings of other users if the parameter is_listed=true. Here is the corresponding code: views.py class ListingViewSet(viewsets.ModelViewSet): """ Viewset for API endpoint that implements CRUD operations for listing(cards for sale). - To perform listing search for all users use base endpoint (api/listing/). - To perform listing search by 'is_listed' use base endpoint with ?is_listed=true/false parameter. - To perform listing search for specific user use base endpoint with ?user_id=<user_id> parameter. - To perform PUT or PATCH use base endpoint with /<listing_id> parameter. """ queryset = Listing.objects.all().order_by('id') serializer_class = ListingSerializer permission_classes = [permissions.IsAuthenticated] filter_backends = [DjangoFilterBackend] filterset_class = ListingFilter def get_queryset(self): user = self.request.query_params.get('user_id', None) if user: if [IsOwner()]: return self.queryset.filter(user=user) return self.queryset def perform_create(self, serializer): serializer.save(user=self.request.user) urls.py urlpatterns = [ path('', views.ListingViewSet.as_view({'get': 'list', 'post': 'create'}), name='listing'), path('<int:pk>/', views.ListingViewSet.as_view( {'get': 'retrieve', 'put': 'update', 'delete': 'destroy', 'patch': 'partial_update'}), name='listing_detail'), ] serializers.py class ListingSerializer(serializers.ModelSerializer): card_name … -
Django existing db records not found in testcase when using postgresql
ubuntu 22.04, mysql 8.0.35, postgresql 16.1, python 3.8.18, django 4.2 django default db = "mydb" We have a large data set saved in "mydb", generating that takes a long time. While using mysql db, I was able to fetch items from "mydb" like <ModelName>.objects.filter() in my test cases. I'm unsure if records are copied into "test_" db from "mybd" by django. Then I switched to postgres, recreated the data. When I fetch the data in APiView, it's working fine. But in testcases all model queries return blank queryset. Is there a workaround for testcases while using postgres so I would not have to recreate the data every time I run the tests ? Thanks. -
I am building Django Web Application .I am using rest-framework but i am so confused How to intregate django rest-framework with frontend
Like this method i am getting the data but how will i render the data in html file `@api_view(['POST']) @authentication_classes([JWTAuthentication]) @permission_classes([IsAuthenticated]) def homeapi(request): try: data = json.loads(request.body.decode('utf-8')) print(data) # Dummy student data (replace this with your logic to fetch real data from a database) dummy_students = [ {'id': 1, 'name': 'Alice', 'age': 20, 'grade': 'A'}, {'id': 2, 'name': 'Bob', 'age': 22, 'grade': 'B'}, {'id': 3, 'name': 'Charlie', 'age': 21, 'grade': 'C'}, # Add more students as needed ] # Return student details as JSON response return JsonResponse({'students': dummy_students}) except Exception as e: return JsonResponse({'error': str(e)}, status=400)` I am expecting that first i am requesting the data from an API after getting the data i want to show it to the user how will i do that. -
NoReverseMatch at in django
I am making an online quiz site using bootstrap and django. I want to make a system where the admin enters an OTP value that acts as password of every user(I haven't yet made the admin part hence using a constant int value for development purposes only). I have made a form but it is throwing me an error saying : NoReverseMatch at /class10.html/testlanding.html/ Reverse for 'validating_user' not found. 'validating_user' is not a valid view function or pattern name. the following is the files : url.py : from django.urls import path from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns =[ path("", views.homepage, name = "home page"), path ("class10.html/" , views.class10 , name = "Class 10th"), path ("class12.html/", views.class12, name ="class 12"), path ("class10.html/testlanding.html/", views.validating_users, name ="pre test info"), path ("class12.html/testlanding.html/", views.validating_users, name ="pre test info"), path ("class10.html/testlanding.html/testinstruction.html/", views.test_instruction, name ="pre test info"), path ("class12.html/testlanding.html/testinstruction.html/", views.test_instruction, name ="pre test info"), ] views.py from django.shortcuts import render, redirect from django.http import HttpResponse , HttpResponseRedirect from .forms import login_form # Create your views here. def homepage(response): return render (response,"main/index.html",{}) def class10 (response): return render (response, "main/class10.html", {}) def class12 (response): return render (response, "main/class12.html", {}) def validating_users (response): if response.method == "POST": … -
Import errors after upgrading django
After updating Django to version 4.2, I'm having several import issues, for example: "ImportError: cannot import name 'ugettext' from 'django.utils.translation'". All the errors point to the configuration of my virtual environment, which is build using Poetry. I have already cleared the cache and deleted the local directory (Cache). Everything (Django, Python, etc.) is in new versions and are compatible. -
I want user to be able to book for the same table but not at the same time
I have a model caled BookTable and a model Table, i want users to be able to book for the same table but not at the same time but i have no clue how am i going to make it. My BookingTable model... class BookingTable(models.Model): TIME_CHOICES =[ ('08:00', '08:00'), ('09:00', '09:00'), ('10:00', '10:00'), ('11:00', '11:00'), ('12:00', '12:00'), ('13:00', '13:00'), ('14:00', '14:00'), ('15:00', '15:00'), ('16:00', '16:00'), ('17:00', '17:00'), ('18:00', '18:00'), ('19:00', '19:00'), ('20:00', '20:00'), ('21:00', '21:00'), ] table = models.ForeignKey(Table, on_delete=models.CASCADE) user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) time = models.TimeField(default='00:00', choices=TIME_CHOICES) def get_absolute_url(self): return reverse("list_tables") def __str__(self) -> str: return self.user.username + "-" + self.table.name My Table model... class Table(models.Model): name = models.CharField(max_length=100, unique=True) size = models.PositiveIntegerField() image = models.ImageField(upload_to='static/media/images/', default='static/media/images/default.jfif') description = models.TextField(null=False, blank=False, default="This is a very beatiful table") def __str__(self) -> str: return self.name[:50] def get_absolute_url(self): return reverse("list_tables") I don't know where to start from -
Django returning status code 400 with error message from test
I'm trying to run tests from my DJango app, but I'm getting FAIL: test_login (authentication.tests.AuthTestCase) line 32, in test_login self.assertEqual(response.status_code, 200) AssertionError: 400 != 200 This is the code of my test: def test_login(self): data = {'usuario_email': 'voter1', 'password1': '123'} response = self.client.post('/authentication/login/', data, format='json') self.assertEqual(response.status_code, 200) message = response.json().get('message') self.assertEqual(message, 'Autentificación correcta') And this is the code for login: def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data usuario_email = cd.get('usuario_email') password1 = cd.get('password1') user = None if usuario_email and '@' in usuario_email: # Si es un correo electrónico, busca por email user = User.objects.filter(email=usuario_email).first() else: # Si no es un correo, busca por nombre de usuario user = User.objects.filter(username=usuario_email).first() if user is not None: user = authenticate(username=user.username, password=password1) if user is not None and user.is_active: login(request, user) print("Usuario logueado correctamente") return JsonResponse({'message': 'Autentificacion correcta'}) else: return JsonResponse({'message': 'Cuenta desactivada o credenciales inválidas'}) else: return JsonResponse({'message': 'Inicio de sesión inválido'}) return JsonResponse({'error': 'Solicitud incorrecta'}, status=400) I have tried manually to login, and I get {"message": "Autentificacion correcta"} The URL I use for login is http://127.0.0.1:8000/login-form and the URL to make the POST action: http://127.0.0.1:8000/authentication/login/ I have tried to debug the test but I always … -
How connect fromm locally and run make migrations in postgresql docker service?
I am building django aplication and use docker to easy manage this. My docker file for django is : FROM python:3.11 WORKDIR /app ENV PYTHONUNBUFFERED 1 ENV DJANGO_SETTINGS_MODULE=server.settings COPY requirements/prod.txt requirements/prod.txt RUN pip install --no-cache-dir -r requirements/prod.txt COPY . . # Expose the port EXPOSE 8000 # RUN python3 manage.py makemigrations # RUN python3 manage.py migrate # Run the Django application CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] and also docker-compose for postgres is: db: image: postgres:13 container_name: auralab-db environment: POSTGRES_DB: auralab POSTGRES_USER: admin POSTGRES_PASSWORD: admin ports: - "5432:5432" and it is my django settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'auralab', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': 'db', 'PORT': '5432', } } problem is to add make migrations in django dockerfile doesnt works, need connect and define connection for this. Actual error is then i have to access databse it has error: ProgrammingError at /api/learning/syllabus/ relation "learning_syllabus" does not exist LINE 1: ...abus"."results", "learning_syllabus"."hours" FROM "learning_... ^ -
Problem with Python suddenly goes Internal error in Azure
I'm pretty new in Python I only worked with it 3 months and I must take care with this implantation in my current job. The thing is the Django Web App inside Azure suddenly throws Internal Error Monday the Web App was working without problem, yesterday suddenly stopped working and throws Internal Error . The log is the next one. 2023-12-13T10:00:49.303444248Z: [ERROR] [2023-12-13 10:00:49 +0000] [108] [ERROR] Error handling request / 2023-12-13T10:00:49.303502748Z: [ERROR] Traceback (most recent call last): 2023-12-13T10:00:49.303508848Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/gunicorn/workers/sync.py", line 135, in handle 2023-12-13T10:00:49.303512948Z: [ERROR] self.handle_request(listener, req, client, addr) 2023-12-13T10:00:49.303516548Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/gunicorn/workers/sync.py", line 178, in handle_request 2023-12-13T10:00:49.303520448Z: [ERROR] respiter = self.wsgi(environ, resp.start_response) 2023-12-13T10:00:49.303523948Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 124, in __call__ 2023-12-13T10:00:49.303527548Z: [ERROR] response = self.get_response(request) 2023-12-13T10:00:49.303530848Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 139, in get_response 2023-12-13T10:00:49.303534548Z: [ERROR] set_urlconf(settings.ROOT_URLCONF) 2023-12-13T10:00:49.303537748Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/django/conf/__init__.py", line 104, in __getattr__ 2023-12-13T10:00:49.303541248Z: [ERROR] val = getattr(_wrapped, name) 2023-12-13T10:00:49.303544547Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/django/conf/__init__.py", line 331, in __getattr__ 2023-12-13T10:00:49.303548047Z: [ERROR] return getattr(self.default_settings, name) 2023-12-13T10:00:49.303551347Z: [ERROR] AttributeError: module 'django.conf.global_settings' has no attribute 'ROOT_URLCONF' I know what it seems... but I double checked all configurations, maybe is something that I'm missing... This is a snippet from settings.py I can't share publicly the entire file but the folder hierarchy … -
Problem with Error 502 when run app on server
I am beginner in Python and Django. I have his code: def force_resend(self): # without this code app run ok url = settings.PAYMENT_GATEWAY_URL + "payments/" + self.secretkey+ "/" + settings.PAYMENT_POS_ID + "/resend/" req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE data = urllib.request.urlopen(req,context=ctx) contents = data.read().decode('utf-8') contents = '{"status": "OK", "payments_accepted": 1, "payments_count": 1, "payments_declined": 0}' data = json.loads(contents) return data I try this code too: def force_resend_transaction(self): h = httplib2.Http(disable_ssl_certificate_validation=True) resp, content = h.request(settings.PAYMENT_GATEWAY_URL + "payments/" + self.secretkey+ "/" + settings.PAYMENT_POS_ID + "/resend/") # # content = '{"status": "OK", "payments_accepted": 1, "payments_count": 1, "payments_declined": 0}' c = json.loads(content) return data When I run this code on my local PC - it's work without any problems. When i try run this in my Kubernetes, i have Error 500. Other functions in my app work correctly. Problem is only with this method. How can i fix them? I use Python 3.8 Please help me :)