Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue: FOREIGN KEY constraint failed
so I'm currently writing a function to let the user write a review. Tho I'm having issues when the user goes to submit the review. It tells me that FOREIGN KEY constraint failed I know that it is a very simple issue, but I cant really see the solution The TracBack is: Traceback (most recent call last): File "/workspace/webster00/products/views.py", line 84, in submit_review review = ReviewRating.objects.get(user=request.user.userprofile, product_id=product_id) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/query.py", line 435, in get raise self.model.DoesNotExist( During handling of the above exception (ReviewRating matching query does not exist.), another exception occurred: File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception: File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/workspace/webster00/products/views.py", line 99, in submit_review data.save() File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py", line 763, in save_base updated = self._save_table( File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py", line 906, in _do_insert return manager._insert( File … -
DJANGO how can make only owner the post edit and delete
sorry for bad english im arabic and first im new here i wnat know how "DJANGO" how can make only owner the post edit and delete and THANK YOU I Try this in the tmplates for only how owner the post can he edit and delete {% if user.id == books.username.id %} <h1><a href="{% url 'books:book_delete' books.id %}">delete</a></h1> <h1><a href="{% url 'books:user_edit_book' books.id %}">update</a></h1> {% endif %} -
Sharing models between Django apps yields: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I have a Django project with multiple apps set up like: myproject/ - apps/ - app1/ - app2/ Everything works when running python manage.py runserver until I need to share models in app1 with app2. It seems this should be as simple as adding a standard import statement in the appropriate file in app2, e.g: # myproject/apps/app2/callback_funcs/sub_functions.py from apps.app1.models import SharedDataModel Unfortunately, as soon as I add the import statement, I get the error django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I tried solutions given here, here, and here, yet the problem persists. All apps are in my INSTALLED_APPS list and being read correctly (again, as long as I exclude the problematic import statement above). I thought the order of the apps in the INSTALLED_APPS list might be an issue (I've seen instructions elsewhere that state certain apps need to be first) but this doesn't seem to affect the results. I have: INSTALLED_APPS = [ ... 'apps.app1', 'apps.app2.app', ... ] app1 is a standard Django app, app2 is a Django Plotly Dash app and has an app file which contains: # myproject/apps/app2/app.py from django_plotly_dash import DjangoDash from .layout import layout from .callbacks import register_callbacks app = DjangoDash("app2") app.layout = layout register_callbacks(app) Interestingly, … -
How to set encoding on a postgres connection using a dj-database URL?
dj-database-url allows setting a postgres URL on a connection. For example: # python DATABASES = { 'default': dj_database_url.config() } # environment variable export DATABASE_URL=postgres://user:pw@localhost:port/dbname However, I inexplicably find that the DB connection has a SQL_ASCII encoding instead of UTF8 like I want. Here is one workaround for psycopg2, explicitly setting the client encoding on the connection. How do I do that with an implicit connection defined by DATABASE_URL? -
I want to implement calculation
Models: class TrainingProgram(TimeStampModel): name = models.CharField(max_length=100, verbose_name="Name", unique=True) slug = AutoSlugField(populate_from="name", unique=True, verbose_name="Slug") class Meta: verbose_name = "Training Program" verbose_name_plural = "Training Programs" db_table = "training_programs" class Course(TimeStampModel): name = models.CharField(max_length=100, verbose_name="Name", unique=True) slug = AutoSlugField(populate_from="name", unique=True, verbose_name="Slug") training_program = models.ForeignKey("training.TrainingProgram", on_delete=models.CASCADE, related_name='courses') class Meta: verbose_name = "Course" verbose_name_plural = "Courses" db_table = "courses" class CourseOutline(TimeStampModel): course = models.ForeignKey("training.Course", on_delete=models.CASCADE, related_name='outlines') name = models.CharField(max_length=100, verbose_name="Name", unique=True) is_active = models.BooleanField(default=True, verbose_name="Active") class Meta: verbose_name = "Course Outline" verbose_name_plural = "Course Outlines" db_table = "course_outlines" class EmployeeTrainingProgram(TimeStampModel): user_profile = models.ForeignKey("users.UserProfile", on_delete=models.CASCADE) training_program = models.ForeignKey("training.TrainingProgram", on_delete=models.CASCADE) is_completed = models.BooleanField(default=False, verbose_name="Completed") start_date = models.DateField(verbose_name="Start Date", ) completion = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="Completion", default=Decimal(0.00)) class Meta: verbose_name = "Employee Training Program" verbose_name_plural = "Employee Training Programs" db_table = "employee_training_programs" class EmployeeCourse(TimeStampModel): user_profile = models.ForeignKey("users.UserProfile", on_delete=models.CASCADE) course = models.ForeignKey("training.Course", on_delete=models.CASCADE) is_completed = models.BooleanField(default=False, verbose_name="Completed") completion = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="Completion", default=Decimal(0.00)) class Meta: verbose_name = "Employee Course" verbose_name_plural = "Employee Courses" db_table = "employee_courses" class EmployeeCourseOutline(TimeStampModel): user_profile = models.ForeignKey("users.UserProfile", on_delete=models.CASCADE) course_outline = models.ForeignKey("training.CourseOutline", on_delete=models.CASCADE) is_completed = models.BooleanField(default=False, verbose_name="Completed") class Meta: verbose_name = "Employee Course Outline" verbose_name_plural = "Employee Course Outlines" db_table = "employee_course_outlines" Serializer: class OutLineSerializer(serializers.ModelSerializer): course_display = serializers.CharField(source="course.name", read_only=True) class Meta: model = CourseOutline fields = '__all__' … -
Wait before fetching django objects if database transaction is ongoing
I have a python script which uses pandas to read an SQL Server table and then transfer it to a PostgreSQL database as it is. This happens every 10 minutes with a linux cron job. Whenever pd.to_sql is called it takes 1 minute for the table to be written to postgres. In Django i have an unmanaged model for this table and my problem is that if i use MyModel.objects.all() during the 1 minute that the pd.to_sql takes to run, I get no objects back. That's because in pd.to_sql I'm using if_exists='replace'. Although this is expected behavior, is there any way to "wait" somehow while executing MyModel.objects.all() while there's an insert going on in the database ? How should i approach this problem ? I have read about isolation level but I dont know if i should mess with that and if it will fix my problem. I also read about django's transaction.on_commit() but it's not for my case -
user with this email address already exists in postman but admin panel creates it
I have a custom user and profile model correlated. When I want to create new profile via Postman for this user I get user with this email address already exists //im using this json on Postman { "user":{ "email": "admin@gmail.com" }, "gender": "1", "bio": "test", "playlist": "qwerts", "gym": { "id": "74038574-51fa-4945-89b2-666c2888ebbb", "name": "testname", "date": "2023-03-12T14:21:54.835946Z", "place": "a897f045-da6d-4d7c-a706-9878b77128de" } } But when I'm in the admin panel I can easily create one I wanted to check what will happen when I pass an email that does not exist as a user The `.create()` method does not support writable nested fields by default. Write an explicit `.create()` method for serializer `user_mgmt.serializers.ProfileSerializer`, or set `read_only=True` on nested serializer fields. I suppose that those errors are not correlated but im posting it anyways just for diligence and probably i have errors in the same functions views.py class ProfileViewSet(viewsets.ModelViewSet): serializer_class = ProfileSerializer def get_queryset(self): return Event.objects.all() def create(self, request): serializer = ProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() data = serializer.data return Response(data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User exclude = ('password', 'is_superuser', 'is_staff', 'groups', 'user_permissions') class ProfileSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Profile fields = '__all__' depth = … -
Accessing POST data in a django CreateView
I am trying to use PurchaseCreateView to create a Purchase instance and then go on to update the Ingredients model The following code is throwing a MultiValueDictKey error. I CANNOT work out how to fix this. Can anyone help? Here are my Models: class Ingredient(models.Model): name = models.CharField(max_length=30) quantity = models.FloatField() price = models.FloatField() def __str__(self): return self.name def get_absolute_url(self): return "inventory" class MenuItem(models.Model): name = models.CharField(max_length=50) price = models.FloatField() def available(self): return all(x.enough() for x in self.reciperequirements_set.all()) def __str__(self): return self.name class RecipeRequirements(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) quantity = models.FloatField(default=0) def enough(self): return self.quantity <= self.ingredient.quantity def __str__(self): return f"{self.menu_item} requires {self.ingredient}" class Purchase(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.menu_item} purchased at {self.timestamp}"` My Views: ''' class PurchaseCreateView(CreateView): template_name = "inventory/purchase_form.html" model = Purchase fields = "all" success_url = reverse_lazy("home") def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["menu_items"] = [x for x in MenuItem.objects.all() if x.available()] return context def post(self, request): menu_item_id = request.POST["menuitem"] menu_item = MenuItem.objects.get(pk=menu_item_id) purchase = Purchase(menu_item=menu_item) purchase.save() ''' and the template: ''' {% extends 'base.html' %} {% block head %} <title>New purchase</title> {% endblock %} {% block content %} <h2>Add a new purchase</h2> <form method="POST"> {% csrf_token … -
django-simple-history doesn't create any historical data
In my application, I have a model DataSeriesModel and my migration file for this model looks like this: migrations.CreateModel( name='DataSeriesModel', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('id', model_utils.fields.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('name', models.CharField(max_length=255)), ... After adding history = HistoricalRecords() field to the model and running makemigrations I'm getting another migrations file with the content as follows: operations = [ migrations.CreateModel( name='HistoricalDataSeriesModel', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('id', model_utils.fields.UUIDField(db_index=True, default=uuid.uuid4, editable=False, primary_key=True)), ('name', models.CharField(max_length=255)), ... ('history_id', models.AutoField(primary_key=True, serialize=False)), ('history_date', models.DateTimeField(db_index=True)), ('history_change_reason', models.CharField(max_length=100, null=True)), ('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)), ('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)), ], Thera are two primary keys in this migration file and of course after migrate command we're getting: django.db.utils.ProgrammingError: multiple primary keys for table "data_series_models_historicaldataseriesmodel" are not allowed LINE 1: ...cription" text NULL, "history_id" serial NOT NULL PRIMARY KE... When I tried to manually set history_id to for example models.IntegerField() the migrate command worked without errors, but I didn't get any historical records in the database. What could be wrong? What can I try/change to get any historical records? -
Object of type '__proxy__' is not JSON serializable
When I want to import variants in a CSV file format then this error occurred. Here is the code: @api_view(["POST"]) @permission_classes((permissions.IsAuthenticated,)) def CSVBulkUpdate(request, model, pk=None): user = User.objects.get(id=request.user.id) mapped_obj_to_import = [] data = request.data["data"] mapped_obj = request.data["mapped_obj"] print(data) for row in data: row_obj = {} if row.get("id") or row.get("name"): for key, item in mapped_obj.items(): if item and row.get(key) != "": row_obj[item] = covertObjects(item, row.get(key)) mapped_obj_to_import.append(row_obj) try: if model == "product": csvBulkUpdate(user.id, mapped_obj_to_import) else: csvVariantBulkUpdate(user.id, mapped_obj_to_import) except Exception as e: print("Error: ", str(e)) return Response({"data": str(e)}, status=400) return Response({"data": "success"}, status=200) The csvVariantBulkUpdatefunction code: def csvVariantBulkUpdate(user, dataToUpdate): serializer_class = serializers.VariantImportUpdateSerializer model = models.Variant serializer_unapproved_class = serializers.UnapprovedVariantImportSerializer module = "variant" view = "Variant" list_data = dataToUpdate user = User.objects.get(id=user) print(user) variants = [] relational_fields = ["size", "color"] results = {"success": {}, "failure": {}} for i, item in enumerate(list_data): results["failure"][item["id"]] = {} try: record = model.objects.get(id=item["id"]) item["product"] = record.product.id if user.is_admin: print("variant update admin view triggered") update_size_in_approved = False update_color_in_approved = False if "size" in item: error, data = sizesValidate(item["size"]) if error: results["failure"][item["id"]]["size"] = data item["size"] = data update_size_in_approved = True if "color" in item: error, data = colorValidate(item["color"]) if error: results["failure"][item["id"]]["color"] = data item["color"] = data update_color_in_approved = True if len(results["failure"][item["id"]]) == … -
How to inherit from a model to use its fields but be an independant table in Django?
I have a CompanyRanking model: class CompanyRanking(): """Company ranking model. Rankin hold a top based on minutes usage for user. """ company = models.ForeignKey( 'companies.company', on_delete=models.CASCADE, null=True, related_name='ranking' ) user = models.ForeignKey( 'users.user', on_delete=models.CASCADE, null=True, related_name='ranking_position' ) extra_data = models.JSONField( null=True, blank=True ) I need to create another model with the same information as CompanyRanking but with an extra relation to another table (CompanyBatchByDate) in which I get the dates to filter the users's points and show other ranking. I am trying to inherit from CompanyRanking as shown: class CompanyRankingByBatch(CompanyRanking): """ Company ranking model based on batch. """ batch = models.ForeignKey( 'companies.CompanyBatchByDate', on_delete=models.SET_NULL, null=True, related_name='ranking_by_batch', ) class CompanyBatchByDate(): """ Company ranking model based on batch. """ company = models.ForeignKey( 'companies.company', on_delete=models.CASCADE, null=True, related_name='batch_by_date' ) initial_date = models.DateField( null=True, blank=True, help_text='Date when the batch start' ) finish_date = models.DateField( null=True, blank=True, help_text='Date when the batch finish' ) is_active = models.BooleanField( default=True, help_text='Batch that will be used to calculate the ranking' ) name = models.CharField( max_length=255, null=True, blank=True, help_text='Name of the batch' ) Problem is, I want to be able to have a differente related_name of the relationship of user - companyrankingbybatch and want to update this model fields independently from CompanyRanking. … -
Django List Admin Is Very Slow When Setting is_editable to use a Django Money Field
I'm utilizing the django-money package in my model like so. class MyModel(models.Model): price_low = MoneyField( max_digits=10, default=0, decimal_places=2, null=True, blank=True, default_currency="USD", ) price_medium = MoneyField( max_digits=10, default=0, decimal_places=2, null=True, blank=True, default_currency="USD", ) price_high = MoneyField( max_digits=10, default=0, decimal_places=2, null=True, blank=True, default_currency="USD", ) And then loading the models in an Admin List with these fields set as editable like so. class IssueAdmin(admin.ModelAdmin): list_editable = ( "price_low", "price_medium", "price_high" ) list_per_page = 20 With this setup and 400k records in the database it takes approx. 6 seconds to load the page. I'm limiting the results returned to 20 just to get this page to return in somewhat of a respectable time frame. If I remove the money fields from list_editable and put different fields that are basic inputs or even autocompletes the page loads in approx 1.5 seconds. How can I improve the performance of this? -
update_or_create with django JSONField
I use Django JSONField to save custom objects (that are callable) and i am confused by update_or_create. My custom objects could be realized by nesting enough dictionarys but that is a pain to work with. Thats why i want to use custom objects. I didn't want to use a Django Model for that object, as i worry about the amount of database requests. My Minimum example:models.py from django.db import models import json # Create your models here. class F: def __init__(self, val) -> None: self.val = val def __call__(self): return "call_return_string" def to_serializable(self) -> dict: return {"class": "F", "val": self.val} @classmethod def from_serialized(classtype, dic): assert "class" in dic.keys() assert dic["class"] == "F" return F(dic["val"]) class FEncoder(json.JSONEncoder): def default(self, f: F) -> dict: return f.to_serializable() class FDecoder(json.JSONDecoder): def F_obj_hook(self,dic:dict): if "class" in dic.keys(): if dic["class"] == "F": return F.from_serialized(dic) return dic def __init__(self,*args,**kwargs): super().__init__(object_hook=self.F_obj_hook,*args,**kwargs) class Tester(models.Model): id = models.BigAutoField(primary_key=True) data= models.JSONField(default=dict,encoder=FEncoder,decoder=FDecoder) Let f = F("1"). Now when i run any of these: #Tester.objects.create(data=f) #works as expected #Tester.objects.filter(id=1).update(data=f)#works as expected #Tester.objects.get(data=f)#works as expected #Tester.objects.update_or_create(data=f,defaults={"data":f}) #not as expected The first will create a database entry where the data column is filled with {"class": "F", "val": "1"}. The second would update an existing entry, … -
why Django form show UnicodeEncodeError in Persian language?
I have simple form as below: forms.py: from django import forms class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) views.py: from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import NameForm def get_name(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): print(form.cleaned_data) return HttpResponseRedirect('/') else: form = NameForm() return render(request, 'form.html', {'form': form}) form.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> </body> </html> If I write English character and submit form, it works ok and execute print statement but if I write Persian character like'متن تست' it shows this error: UnicodeEncodeError at / 'charmap' codec can't encode characters in position 132-136: character maps to <undefined> Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 4.1.7 Exception Type: UnicodeEncodeError Exception Value: 'charmap' codec can't encode characters in position 132-136: character maps to <undefined> Exception Location: C:\Program Files\Python311\Lib\encodings\cp1252.py, line 19, in encode Raised during: myapp.views.get_name Python Executable: C:\python\test1\venv\Scripts\python.exe Python Version: 3.11.2 Python Path: ['C:\\python\\test1', 'C:\\python\\test1', 'C:\\Program Files\\JetBrains\\PyCharm ' '2022.3.2\\plugins\\python\\helpers\\pycharm_display', 'C:\\Program Files\\Python311\\python311.zip', 'C:\\Program Files\\Python311\\DLLs', 'C:\\Program Files\\Python311\\Lib', 'C:\\Program Files\\Python311', 'C:\\python\\test1\\venv', 'C:\\python\\test1\\venv\\Lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2022.3.2\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] Server time: Tue, 14 Mar 2023 19:06:06 +0000 The string that could not … -
Django auth_user programmingerror when running makemigrations or migrate command
I've searched for this problem over stackoverflow and most of the answers are just to run manage.py makemigrations and manage.py migrate but both those commands fail for me. Whenever I try to start my django application I run into the following error message: django.db.utils.ProgrammingError: relation "auth_user" does not exist LINE 1: SELECT "auth_user"."id" FROM "auth_user" Here is my settings.py: INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'simple_history', 'drf_multiple_model', 'backend', 'corsheaders', 'authentication', 'pipeline', 'positions', 'request', ] I can fix this problem if I comment out all my urls in backend/urs.py except for my home url, then I can run makemigrations and migrate. After, I have to uncomment those urls and re-run both makemigrations and migrate. This is the backend/urls.py file: urlpatterns = [ path('', views.UsersListAPIView.as_view(), name="Get Users"), path('<int:pk>/', views.UsersDetailAPIView.as_view(), name="Get Users"), path('login/', views.UserLoginAPIView.as_view()), path('logout/', views.UserLogoutAPIView.as_view()) ] I know how to solve the problem I just don't want to have to do this every time I start my backend. I am going to be using docker containers and would like if the backend just started without issue. I have a migrations folder for every module that has a modules.py and each of these migrations folder have a init.py. Also … -
I have problem with csrf-token when I send reuest with axios
When I send request with axios to my server from 3000 port to 8000 I got 403 forbidden error. But when I send reqest from postman I don't have this error. I am using withCredentials param. And I got csrf token, but when I am sending request on login page I am getting 403 forbidden. How I can get sessionid? axios.get('http://localhost:8000/', { withCredentials: true }) .then((response) => { // const cookies = response.headers['Set-Cookie'] console.log('res', response); let csrf = document.cookie.split('=')[1] console.log('cookie', document.cookie); console.log(csrf); axios.post('http://localhost:8000/', { password: '12345678', username: 'admin@admin.com', csrfmiddlewaretoken: csrf // csrfmiddlewaretoken: 'Njqa9oV5mWmT6fjJhqOYNu8cZ23LgPWK' }, { headers: { // 'X-CSRFToken': csrf, // 'csrftoken': csrf // 'X-CSRFToken': 'Njqa9oV5mWmT6fjJhqOYNu8cZ23LgPWK', // 'X-CSRFToken': csrf, // 'Cookie': `csrftoken=${csrf}` }, withCredentials: true }) .then(res => { console.log('post res', res); console.log(document.cookie) // axios.get('http://localhost:8000/api/devices/v2/thermostats/', { axios.get('http://localhost:8000/api/devices/v2/thermostats/', { headers: { 'X-CSRFToken': csrf, }, withCredentials: true }) .then(res => { console.log('get', res); }) }) }); -
Django: Redirect doesn't work after paypal payment, how to do it right
just like in the title. The redirect is not working after making a paypal payment. The view itself executes correctly but at the end it does not redirect to the correct page. I solved it quite breakneckly by making another view and redirecting it like this window.location.href = "{% url 'order_complete' %}"; but it doesn't look very nice cart.html {% if not item_list %} <p>Cart is empty</p> {% elif user.if_address %} <p>Address is not complete</p> {% else %} <input type="radio" id="pickup" value="pickup" name="shipping" checked/>Personal Pickup <input type="radio" id="inpost" value="inpost" name="shipping"/>Inpost <div id="paypal-button-container"></div> {% endif %} </div> </div> </aside> </div> </div> </section> <script src="https://www.paypal.com/sdk/js?client-id=ASSy-9ZwcMqTUmhxXQbvWkM6gGMm0ZpY-fpQJoMxMTxXHU0qxKVerVhwZSGfJxqUleLOYu5YADkZbTH1&currency=USD"></script> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); var total = "{{ price }}" var url = "{% url 'Checkout' %}" var shippingMethod = "None" paypal.Buttons({ createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: total } }] }); }, onApprove: function(data, actions) { … -
Django form category not showing
I am writing a code for django blogging website it is complete but while adding section of categorizing the list of categories in drop down list in not coming why is that . please anyone help me its urgent for submission of minor project i tried everything i could this is my add post.html {%extends "base.html"%} {% block title %}Add Post{% endblock title %} {% block content %} <h1 style="text-align: center; font-family: 'Open Sans', sans-serif; font-size: 48px; font-weight: bold; color: rgb(174, 255, 229); text-transform: uppercase; letter-spacing: 4px;"> ADD YOUR POST HERE</h1> <table> {% if user.is_authenticated %} <form class="form-control" action="/add_post/" method="post"> {% csrf_token %} <div class="container " style="border:5px solid rgb(0, 0, 0) ; border-radius: 15px; background-color: white;"> {{form.as_p}} <div class="d-flex justify-content-center"> <button class="btn btn-outline-dark" style="position: relative; margin-bottom:20px ;" type="submit">Post</button> </div> </div> </form><br><br> {%endif%} </table> <div class="d-flex justify-content-start container"> <a class="btn btn-dark" style="position: relative;" href="{%url 'Home'%}">Back</a> </div> {% endblock %} this is my forms.py from dataclasses import fields from logging import PlaceHolder from operator import mod from tkinter.ttk import Widget from turtle import title from xml.etree.ElementTree import Comment from django import forms from .models import Post from .models import Comment from django import forms from .models import Category class PostForm(forms.ModelForm): class Meta: … -
Django - how to remove item from dictionary in template?
In my view in Django I have such a function def index(request): user_list = Users.objects.all() page = request.GET.get('page', 1) per_page = request.GET.get('per_page', 10) paginator = Paginator(user_list, per_page) total = paginator.count GET_params = request.GET.copy() try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, 'polls/index.html', { 'users': users, 'total': total, 'GET_params': GET_params}) In my template I try to use passed GET_params to pagination {% if GET_params %} <a href="?{{GET_params.urlencode}}&page={{ i }}">{{ i }}</a> {% else %} <a href="?page={{ i }}">{{ i }}</a> {% endif %} The reason for what I am doing is that i need to pass many parameters like per_page and page in one URL. The problem is, that above code works by multiply page parameters in every single click of url: /?page=1&page=2&page=3... Is there any way to remove from GET_params dictionary (in template!) all values by given key name? I've tried to remove values from GET_params in a view, but it is not the correct way, because I need a last value of all GET parameters in every request. -
Django gives Field error when passed in a function. Django
I want to order the albums with the 10 highest reviews, but when I order by the function "averageReview' it gives me a field error, what is the solution? views: def homeview(request): highest_rated = albums.objects.order_by('-averageReview')[9] album = albums.objects.all() return render(request, "home/home.html", {'albums' : album, 'highest_rated' : highest_rated }) models: class albums(models.Model): title = models.CharField(max_length=100) description = models.TextField() release_date = models.CharField(max_length=10) artist = models.CharField(max_length=100) genre = models.CharField(choices=GENRE_CHOICES, max_length=20) image = models.ImageField(default='default2.jpg', upload_to='album_pics') @classmethod def averageReview(self): reviews = ReviewRating.objects.filter(album=self, status=True).aggregate(average=Avg('rating')) avg = 0 if reviews['average'] is not None: avg = float(reviews['average']) return avg def __str__(self): return self.title class ReviewRating(models.Model): album = models.ForeignKey(albums, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=100, blank=True) review = models.TextField(max_length=1500, blank=True) rating = models.FloatField() ip = models.CharField(max_length=20, blank=True) status = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.subject or f"ReviewRating #{self.pk}" -
Django app works when URLconf is empty, but sub directories are not being routed to Django
There are a lot of questions here regarding the urls.py issues with Django. A lot seems to depend on how the web server is set up. Running locally in development mode, I get no problems with my Django app, but onced deployed to the webserver, it fails. the project urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('search.urls')), path('admin/', admin.site.urls), ] the app urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.search, name='search'), path('search/', views.search, name='search'), ] views.py def search(request): return HttpResponse("You're at the search page.") The empty path works domain.com/app/ the 'include("search.urls")' works, but the path domain.com/app/search/ and 'domain.com/app/admin' do not. Instead the '/app/search/' directs to a 404 not found page outside the django app. So there is something going on with the webserver that sub directories are not being routed to the Django app. Any help is appreciated. The app is running on a Linux Apache 2.4.55 shared hosting server. I have checked the raw error logs and other answers that were related to internal django urlconf issues but this seems to be outside of django. I am looking at this site: https://thecodelearners.com/deploy-django-web-application-to-apache-server-step-by-step-guide/#create_and_configure_conf_file_for_django_app But it is a … -
How to hash stored passwords in mysql using pbkdf2_sha256 using Django
I have list of user passwords stored as plain text. I think I need a script to run over the stored passwords and hash them. I'm new to Django and not sure where to start or how. I created login and creating accounts only works for new users: @admin_login_required def add_emp(request): if request.method == 'POST': user_name = request.POST['user_name'] user_email = request.POST['user_email'] user_otj = request.POST['user_otj'] user_password = pwo.generate() user_password1 = make_password(user_password) empObj = User.objects.create(user_name=user_name, user_email=user_email, user_password=user_password1, user_otj=user_otj) if empObj: subject = 'Advanced Analytics Portal - Login Info' message = f'Name : {user_name}, \n Email : {user_email}, \n Password : {user_password} \n FROM - AA Portal' email_from = settings.EMAIL_HOST_USER send_mail(subject, message, email_from, [user_email]) messages.success(request, "Employee was added successfully!") return HttpResponseRedirect('/create-emp') else: messages.error(request, "Some error was occurred!") return HttpResponseRedirect('/create-emp') return render(request, 'AddEmp.html') def user_login(request): if request.method == "POST": user_email = request.POST['user_email'] user_password = request.POST['user_password'] user_details = User.objects.filter(user_email=user_email).first() if user_details and check_password(user_password, user_details.user_password): request.session['logged_in'] = True request.session['user_email'] = user_details.user_email request.session['u_id'] = user_details.user_email request.session['user_name'] = user_details.user_name request.session['u_type'] = "emp" return HttpResponseRedirect('/user_index') else: return render(request, 'EmpLogin.html', {'msg': "0"}) else: return render(request, 'EmpLogin.html') How can I make previous users log in without creating new accounts for them. -
Django inserting into mySQL database with validate_unique() and save() and a composite primary key
I am trying to insert data into a mySQL database directly from a Django web application I am building. The table I am trying to insert into is called Athlete_T and has a composite primary key value including: 'Fname', 'Lname', and 'DOB'... although Django only allows you to specify one primary key... In my models page I have 'Fname' set to the primary key, as well as a Meta class with a 'unique together' field including the primary key attributes that should specify what qualifies as unique upon inserting a new row into the table. Finally I have my views, where I am getting input from the user and setting all the values equal within an ORM query and using .save() to create a new database entry according to the information provided and entered by the user. According to Django documentation... I should be able to use "Model.validate_unique()" which should check the "unique together" field. I keep getting this error when trying to add a value that has the same "Fname" but the other primary key values are different. Does anyone have any ideas on how to fix this issue or what I am doing wrong? I have tried making … -
Django get context foreign key values
Hi i want to get the values of the foreign key of the object and return it as json models.py message_types = [('txt','text'),('img','image'),('stkr','sticker')] class Images(models.Model): image = models.ImageField(upload_to='static/img/sent/',blank=True,null=True) class MessageType(models.Model): type = models.CharField(max_length=100,choices=message_types) text = models.TextField(blank=True,null=True) image = models.ForeignKey(Images,on_delete=models.CASCADE,blank=True,null=True) sticker = models.ImageField(upload_to='static/stickers',blank=True,null=True) class Message(TrackingModel): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) sender = models.ForeignKey('auth.User', on_delete=models.CASCADE) message_type = models.ForeignKey(MessageType,on_delete=models.CASCADE) readed = models.BooleanField(default=False) def __str__(self) -> str: return f'From <Thread - {self.thread}>' views.py context['messages'] = Message.objects.filter(thread=obj).order_by('-created_at') data = serializers.serialize("json", context['messages']) return JsonResponse({'messages':data}, safe=False) i want to be able to access image.url and message.type i've tried to set depth=2 in the serializer but it doesn't work because i'm using a higher version of Django. -
How to have multiple Django adminsites with different themes
I've exactly the same question so I took his text and adapted it because he didn't had any answer. I hope I'll have more luck than him. I have setup a Django project to use both the default admin site and then I have created a separate adminsite. I did this by subclassing admin.AdminSite and registering models with this other admin and it works exactly as intended. However, I want to use a template such as AdminLTE or Jazzmin with this other admin while sticking with the standard admin theme for the default admin site. I do not know how to do this or if it is even possible. I've read this post, this one, which is related to the previous one, and that one but they seem to deal with just some html files and not a whole template like AdminLTE. I tried to use the index_template attribute and the index.html of AdminLTE but it doesn't display my models but the preview of AdminLTE. Maybe one solution should be to create another project, associate it with the db of my main project and add the lines in settings.py as described there but it's not seem to be a pretty …