Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter and fetch using select_related and prefetch_related in django
Here are my below models: class City(models.Model): city = models.CharField('city name', max_length=25) class Pincode(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE, related_name='city_pincode') pincode = models.PositiveIntegerField('pincode', unique=True) class Vendors(models.Model): pincode = models.ManyToManyField(Pincode, related_name='pincode_vendor') shop_name = models.CharField('Shop name(English)', max_length=50) class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category_subcategory') vendor = models.ForeignKey(Vendors, on_delete=models.CASCADE, related_name='vendor_subcategory') class ItemGroup(models.Model): name = models.CharField('name', max_length=50, unique=True, blank=True) class Item(models.Model): subcategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE, related_name='subcategory_item') itemgroup = models.ForeignKey(ItemGroup, on_delete=models.CASCADE, related_name='itemgroup_item') name = models.CharField('name', max_length=255) I am trying to fetch all the subcategories using fields itemgroup and pincode from models Item and Itemgroup. Here is my code: SubCategory.objects.filter(vendor__pincode__pincode=500071).prefetch_related(Prefetch('subcategory_item', queryset=Item.objects.filter(itemgroup__name='Biryanis') )) Here is i am getting all the items in the subcategory model. But i want only those subcategories whose itemgroup='Biryanis' and pincode='500071'. -
Django beginner NoReverseMatch Reverse not found
Tried many fixes of this problem but somehow cannot fix it regardless. I'm building a betting website path that has a structure like matches/upcoming/int:pk/new_bet.html When i added a bit of code that has to redirect to /new_bet.html the previous /int:pk/ shows this NoReverseMatch error. I do understand that it is because of something I didn't mention in the template for detail.html but i don't know what :( Using python 3.8.2 and django 3.0.6 Related code: models.py from django.db import models from django.utils import timezone from django.urls import reverse from users.models import CustomUser class UpcomingMatches(models.Model): league = models.TextField(blank=True, null=True) date = models.DateTimeField(auto_now_add=False) team1 = models.TextField(blank=True, null=True) team2 = models.TextField(blank=True, null=True) def get_absolute_url(self): return reverse('detail', args=[str(self.id)]) class Bet(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) match = models.ForeignKey(UpcomingMatches, on_delete=models.CASCADE, related_name='new_bet') mvp = models.TextField(blank=True, null=True) def get_absolute_url(self): return reverse('new_bet', args=[str(self.id)]) i marked the troubled line with a comment urls.py from django.urls import path from .views import WelcomePageView, UpcomingMatchesPageView, UpcomingMatchDetailView from .views import new_bet urlpatterns = [ path('', WelcomePageView.as_view(), name="welcome"), path('matches/upcoming/list/', UpcomingMatchesPageView.as_view(), name="upcoming_matches"), path('matches/upcoming/<int:pk>/', UpcomingMatchDetailView.as_view(), name='detail'), path('matches/upcoming/<int:pk>/new_bet/', new_bet, name="new_bet"),] #problem url views.py from django.shortcuts import render, get_object_or_404 from django.views.generic import TemplateView, ListView, DetailView from .models import UpcomingMatches, PastMatches, Bet from .forms import NewBetForm class UpcomingMatchesPageView(ListView): model = … -
I am trying to edit object record
Discription: Hay, when i trying to edit expenses(model) object it redirect me to income(model) with expenses(model) object id and if income(model) object has same id then it edit income(model) object.Please Help ERROR: DoesNotExist at /1/ Income matching query does not exist. model.py from django.db import models import datetime class Income(models.Model): income = models.CharField(max_length=5) date_added = models.DateField(default=datetime.datetime.now, null=True) remark = models.CharField(max_length=100) class Expenses(models.Model): price = models.CharField(max_length=5) date_added = models.DateField(default=datetime.datetime.now, null=True) category = models.CharField(max_length=10, default='Food') remark = models.CharField(max_length=100) form.py from django import forms from .models import Expenses, Income class ExpensesForm(forms.ModelForm): class Meta: model = Expenses fields = '__all__' labels = { 'date_added': 'Date' } def __init__(self, *args, **kwargs): super(ExpensesForm, self).__init__(*args, **kwargs) self.fields['date_added'].required = False class IncomeForm(forms.ModelForm): class Meta: model = Income fields = ('income', 'remark', 'date_added') views.py def addexpenses(request, id=0): if request.method == 'GET': if id == 0: form = ExpensesForm() else: expenses = Expenses.objects.get(id=id) form = ExpensesForm(instance=expenses) return render(request, 'add expenses.html', {'form': form}) else: if id == 0: form = ExpensesForm(request.POST) else: expenses = Expenses.objects.get(id=id) form = ExpensesForm(request.POST, instance=expenses) if form.is_valid(): form.save() return redirect('home') def addincome(request, id=0): if request.method == 'GET': if id == 0: form = IncomeForm() else: income = Income.objects.get(id=id) form = IncomeForm(instance=income) return render(request, 'add income.html', {'form': form}) … -
how to prevent normal users to access the particular html page in django?
I have post creation HTML page in my django project ,I need that page to be accessed only by the admin. Is there any way to prevent the normal user to access the post creation page? -
How to append newly created django object details in a results list with jquery?
I have a one template of question detail and there are multiple answers of this question and below the answer there are replies. While adding the new reply I want to prevent the page refresh so I used ajax and jquery. It creates the reply object in the database without page refresh but I got a problem in displaying that newly created reply object in the replies section. How can i display the newly created reply object details under this div <div id="comment{{answer.pk}}" class="media-heading"> upon creation? views class AnswerReplyView(LoginRequiredMixin, View): login_url = '/' def post(self, request, **kwargs): answer = Answer.objects.get(pk=kwargs['pk']) reply = request.POST.get('reply') reply_obj = AnswerReply.objects.create(answer=answer, reply=reply, replied_by=request.user) data = { 'reply': model_to_dict(reply_obj), } return JsonResponse(data, status=200) template {% for answer in answers %} {% if answer.replies.all %} <div class="media-body"> <div id="comment{{answer.pk}}" class="media-heading"> {% for reply in answer.replies.all %} <small>{{reply.reply}} </small> <span class="time">{{reply.created|timesince}}ago</span> <a href="{% url 'users:user_profile' %}" class="reply">{{reply.replied_by.first_name}} {{reply.replied_by.last_name}}</a><br> {% endfor %} </div> </div> {% endif %} {% endfor %} jquery/ajax {% for answer in answers %} $(function(){ var $commentForm = $('#commentForm{{answer.pk}}') $commentForm.submit(function(e){ e.preventDefault(); e.stopPropagation(); var $formData = $(this).serialize() var $thisURL = $commentForm.attr('action') $.ajax({ method: "POST", url: $thisURL, data: $formData, dataType:'json', csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), success: function (data, textStatus, jqXHR){ var html … -
Export using Django admin import-export give me error
I have installed a import-export extension in my app django, setting the admin.py: from django.contrib import admin from .models import Materiale from import_export.admin import ImportExportModelAdmin from import_export import resources class MaterialeResource(resources.ModelResource): class Meta: model = Materiale class MaterialeAdmin(ImportExportModelAdmin): resource_class = MaterialeResource admin.site.register(Materiale, MaterialeAdmin) All works perfectly, but when I have tried to click on the export button, django give me the following error: Invalid format string Here the Traceback Traceback (most recent call last): File "C:\Users\Federico\Desktop\Prova test\v_env\lib\site-packages\import_export\widgets.py", line 183, in render return self.clean(value).strftime(self.formats[0]) During handling of the above exception (Invalid format string), another exception occurred: File "C:\Users\Federico\Desktop\Prova test\v_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Federico\Desktop\Prova test\v_env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Federico\Desktop\Prova test\v_env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Federico\Desktop\Prova test\v_env\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\Federico\Desktop\Prova test\v_env\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\Federico\Desktop\Prova test\v_env\lib\site-packages\django\contrib\admin\sites.py", line 231, in inner return view(request, *args, **kwargs) File "C:\Users\Federico\Desktop\Prova test\v_env\lib\site-packages\import_export\admin.py", line 482, in export_action export_data = self.get_export_data(file_format, queryset, request=request) File "C:\Users\Federico\Desktop\Prova test\v_env\lib\site-packages\import_export\admin.py", line 460, in get_export_data data = resource_class(**self.get_export_resource_kwargs(request)).export(queryset, *args, **kwargs) File "C:\Users\Federico\Desktop\Prova test\v_env\lib\site-packages\import_export\resources.py", line 900, in export data.append(self.export_resource(obj)) File "C:\Users\Federico\Desktop\Prova test\v_env\lib\site-packages\import_export\resources.py", line 855, … -
How to loop over items of queryset in django template?
PRODUCT_DETAIL = {<Product: 800128249>: [<Vital_info: Black Dial Silicone Strap Watch>, None, <Shipping: 800128249>]} django template: {% for key, value in PRODUCT_DETAIL.items %} <table> {% for item in value %} ... {% endfor %} </table> {% endfor %} I want to write everything stored in <Vital_info: Black Dial Silicone Strap Watch> with heading and values. Is there any way to loop over query sets in such manner? -
Django UpdateView with three different modelforms
I have a django UpdateView which needs to inherit three different models and different models. CreateView is working fine with three different modelforms. models.py: class Employee(models.Model): """ Create employee attributes """ employee_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) e_id = models.IntegerField(unique=True, null=True, blank=True) first_name = models.CharField(max_length=128,blank=True) last_name = models.CharField(max_length=128, blank=True) ..... class WorkExperience(models.Model): """ Stores employee previous work experiences """ employee = models.ForeignKey('Employee', related_name='we_employee', on_delete=models.CASCADE, null=True) previous_company_name = models.CharField(max_length=128, null=True) job_designation = models.CharField(max_length=128, null=True) from_date = models.DateField(null=True) ...... class Education(models.Model): """ Stores employee education background """ employee = models.ForeignKey('Employee', related_name='edu_employee', on_delete=models.CASCADE, null=True) institution_name = models.CharField(max_length=128, null=True) degree = models.CharField(max_length=128, null=True) ..... views.py: class EmployeeUpdateView(LoginRequiredMixin,UpdateView): """ Update a created a employee """ login_url = '/authentication/login/' template_name = 'employee/employee_add_form.html' form_class = EmployeeAddModelForm work_form_class = WorkExperienceForm education_form_class = EducationForm queryset = Employee.objects.all() def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) def get_object(self): id_ = self.kwargs.get("id") return get_object_or_404(Employee, id=id_) WHen I go to Update view, I am only able to update EmployeeAddModelForm values. But other form's(WorkExperienceForm, EducationForm ) fields do not appear let alone edit the values of the fields. I suppose my views.py is not correct. I need suggestion to correct my updateview. -
Handling three forms/model fields with multilevel inheritance in views.py
This may sound creepy. I got three models ; PurchaseBill, PurchaseItem and Inventory. PurchaseBill is the parent PurchaseItem records the products purchased (ForeignKey Relationship with the PurchaseBill - inline formset (dynamic addition with java)) Inventory keeps track of the stock, so it is connected to PurchaseItem to get the quantity purchased and since the inventory obviously is connected to the sales models, that's why I prefer it as a separate model. (Foreignkey or some relationship to the model PurchaseItem - inline formset to PurchaseItem) Here is how my views.py looks like class BillCreate(CreateView): model = PurchaseBill #success_url form_class = PurchaseBillForm def get_context_data(self, **kwargs): data = super(BillCreate, self).get_context_data(**kwargs) if self.request.POST: data['itemform'] = PurchaseItemFormSet(self.request.POST) #data['inventoryform'] = InventoryFormSet(self.request.POST) else: data['itemform'] = PurchaseItemFormSet() #data['inventoryform'] = InventoryFormSet() return data def form_valid(self, form): context = self.get_context_data() itemform = context['itemform'] inventoryform = context['inventoryform'] with transaction.atomic(): self.object = form.save() if itemform.is_valid(): itemform.instance = self.object itemform.save() return super(BillCreate, self).form_valid(form) I am not getting the inputs of InventoryFormSet from the user. I just need to retrieve the instance of PurchaseItem and save the relationship field in the Inventory model and also retrieve the qty field from the PurchaseItem and save it to the "in_stock" field in the inventory model. I … -
django: help using slugs in django
I'm making a Django application and been trying to add a detail_profile_view, i want a button underneath the posts (its a blog app) to direct you to a users account, the following isn't the entirety of my code its only what i think is relevant in the error, if you need more i can always update this post.Thanks for helping i have had this bug for a while now.i keep getting the following error: Internal Server Error: / Traceback (most recent call last): File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\dylan\myblogsite\blog\views.py", line 34, in home_view return render(request, 'home.html', context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 936, in render bit = node.render_annotated(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 903, in render_annotated return self.render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 163, in _render return … -
ModuleNotFoundError: No module named 'fcntl' django on Windows
pip install django-crontab and was trying to run python manage.py crontab add Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv File "C:\Users\navee\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management_init_.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\navee\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management_init_.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\navee\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management_init_.py", line 206, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\navee\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management_init_.py", line 40, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "C:\Users\navee\AppData\Local\Programs\Python\Python36-32\lib\importlib_init_.py", line 126, in import_moduled File "C:\Users\navee\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django_crontab\management\commands\crontab.py", line 4, in from django_crontab.crontab import Crontab File "C:\Users\navee\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django_crontab\crontab.py", line 3, in import fcntl ModuleNotFoundError: No module named 'fcntl' -
save() missing 1 required positional argument: 'self' [closed]
I am working with django rest framework registration and login. this is my serializers.py class clientnameSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = clientname fields = ('id','username','password', 'password2' , 'email') ordering = ['id',] extra_kwargs = { 'password': {'write_only': True} } def save(self): account = clientname( email=self.validated_data['email'], username=self.validated_data['username'] ) password = self.validated_data['password'], password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) account.set_password(password) account.save() return account this is my views.py @api_view(['POST']) def registration_view(request): if request.method == 'POST': serializer = clientnameSerializer(data=request.data) data={} if serializer.is_valid(): account = clientname.save() data['response'] = "successfully registered a new user." data['email'] = account.email data['username'] = account.username else: data = serializer.errors return Response(data) this is the error i get when i tried to register an account Exception Value: save() missing 1 required positional argument: 'self' -
Django select_related throwing exception when trying to select child model
Please help me out. I have two table Patient(models.Model): .... PatientAddress(models.Model): patient = FK(Patient, related_name='address') ... Now how can i get data of PatientAddress from Patient table by one query? When I query Patient.objects.select_related('patientaddress') . It's throwing Invalid field name(s) given in select_related: 'patientaddress'. Please help -
How Price low/high filters work in Django?
I have a list of products on my page, and there are many types of filters, but I want something like this (Suppose, if a user click on price high to low then all product list will be displayed on the same page according to this filter, and suppose if a user click on price low to high then filter work according to lower price to higher and product list will be displayed in lower to high price format, please let me know how I can do this. I want the same functionality in ascending order and descending order in dropdown. here is my models.py file class Product(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) subcategory=models.ForeignKey('SubCategory', related_name='prosubcat', on_delete=models.CASCADE, blank=True, null=True) totalprice=models.IntegerField() saleprice = models.IntegerField() discount = models.IntegerField(default=None) title=models.CharField(max_length=225) description = models.TextField() overview = models.TextField(null=True) featured = models.BooleanField(null=True) trending=models.BooleanField(null=True) image= models.ImageField(blank=True) tags = TaggableManager() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) here is my views.py file... def SubCategorySlugListAPIView(request, subcat_slug): category = Category.objects.all() subcategories = SubCategory.objects.all() product = Product.objects.all() featured=Product.objects.filter(featured=True).order_by('-created_at')[0:6] high = Product.objects.all().order_by('-saleprice') if subcat_slug: subcategory = get_object_or_404(SubCategory, subcat_slug=subcat_slug) productlist = product.filter(subcategory=subcategory) paginator = Paginator(productlist, 12) page_number = request.GET.get('page') product = paginator.get_page(page_number) template_name = 'mainpage/cat-products.html' context = {'product': product, 'subcategories': subcategories, 'subcategory': subcategory, 'category': category, 'featured':featured, 'high':high} … -
Wagtail: How to setup up unittest for simple page edit?
I am trying to setup a simple test in Wagtail with django-pytest and wagtail_factories to test the ability of users to edit Pages they own. But I keep beeing redirect when I try to get the edit url. (For my example here I use a superuser fixture to not have to deal with permissions.) # test_views.py def test_user_can_edit_owned_pages(client, superuser): parent_page = MyPageIndexPageFactory() my_page = MyPageFactory(owner=superuser, parent=parent_page) edit_url = reverse("register_mypage_modeladmin_edit", args=[my_page.pk]) client.force_login(superuser) response = client.get(edit_url) # to capture in pytests output print( superuser.is_superuser, my_page.id, response ) assert response.status_code == 200 The assert fails although the captured output shows that the Page get’s created with the correct ID in the url – but I am beeing redirect nevertheless. True 4778 <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/admin/pages/4778/edit/?next=/admin/my_app/mypage/"> When I get the index url for the list view of my model all is good. [...] index_url = reverse("register_mypage_modeladmin_index") response = client.get(index_url) qs = response.context[0]["object_list"] print(qs) Captured output: <PageQuerySet [<MyPage: Test Page>]> I'd suspect that this is (still) an permissions problem even though I am using a superuser. How would one setup a simple test like this in Wagtail? -
How to use a HTML dropdown value in a different view of Django
I have three urls in django.When I select a value in first url,I want it to be used in view of third url(Page).The navigation is as follows: url1->url2->url3 There is a dropdown in url1 and I want to fetch the selected value in url3. I tried using POST but it doesn't work.Is there any other way? -
Django Joining 4 tables based on 2 ids, change raw sql to django orm
I have Approval table, and i want to calculate the sum of total prices of the procedure based on the company and procedure type. ''' class Approval(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False) company = models.ForeignKey(Company, related_name=("approval_company"), on_delete=models.CASCADE, verbose_name = _('Company')) procedure = models.ForeignKey('Procedure', related_name=("approval_procedure"), on_delete=models.CASCADE, verbose_name = _('Procedure')) def price_calculated(self): price = returnZero(Price.objects.filter(Q(procedure__name=self.procedure.name) & Q(company__name=self.company.name)).aggregate(Max('price'))['price__max']) return price class Procedure(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False) name = models.CharField(_('Name'), max_length=255) class Price(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False) company = models.ForeignKey('Company', related_name=("price_company"), on_delete=models.CASCADE, verbose_name = _('Insurance Company')) procedure = models.ForeignKey('Procedure', related_name=("price_procedure"), on_delete=models.CASCADE, verbose_name = _('Procedure')) price = models.IntegerField(_('Price'), ) class Company(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False) name = models.CharField(_('Name'), max_length=64) ''' i use the price_caluclated function to find the price of each approval, now i want to get all the prices of each approval and .aggregate(Sum('price'))['price__sum']) to get the sum of all prices of the approvals i have. the raw sql for postgresql and if my app is called main is : ''' select main_price.price from main_approval inner join main_price on main_approval.procedure_id = main_price.procedure_id and main_approval.company_id = main_price.company_id ; … -
Azure Container Instances: Create a multi-container group from Django+Nginx+Postgres
I have dockerized a Django project with Postgres, Gunicorn, and Nginx following this tutorial. Now i want to move the application to azure container instances. Can i simply create a container group following this tutorial, and expect the container images to comunicate the right way? To run the project locally i use docker-compose -f docker-compose.prod.yml up -d --build But how is the comunication between the containers handled in azure container instances? The docker-compose.prod.yml looks like this: version: '3.7' services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn hello_django.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db nginx: build: ./nginx volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles ports: - 1337:80 depends_on: - web volumes: postgres_data: static_volume: media_volume: -
Throws "IntegrityError: duplicate key value violates unique constraint" while publishing a page in Django-cms
Recently I migrated my local django + django-cms site to production server using following methods: moved code to production server and populated db schema using makemigration and migrate commands I exported the data using Pycharm's inbuilt database tool via "Dump data to File(s)" > "SQL-Insert-Statements.sql.groovy", the exported file had only insert statements and no other sql statement. I copy pasted and executed these statements in query tool window using pgAdmin 4 I executed sql statements for reset sequences which I got from "python manage.py sqlsequencereset ..." command Now after doing all this the website is working fine but on the admin side I can edit the page and it keeps the changes in database but throws error when I click on "publish page changes" button. Here is the error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "cms_cmsplugin_path_4917bb44_uniq" DETAIL: Key (path)=(0007) already exists. Complete error stack: [15/Jul/2020 21:13:40] "POST /en/admin/cms/page/45/en/publish/ HTTP/1.1" 500 25121 Internal Server Error: /en/admin/cms/page/45/en/publish/ Traceback (most recent call last): File "/home/john/project1/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "cms_cmsplugin_path_4917bb44_uniq" DETAIL: Key (path)=(0007) already exists. The above exception was the direct cause of the following exception: Traceback (most recent call last): File … -
Django-App works locally but unexpected on Heroku
I made a django-app-calendar that changes months with buttons "next"/"prev". With a click on the calendar-link it always goes back to the current month. This works fine when I run it locally. But with Heroku it works just half of the times. When it doesn't work, there are then random jumps. For example by clicking next it jumps from September to February. Sometimes there is also the error: "name 'cd' is not defined <form action="/calendar/" method="post"> {% csrf_token %} <button name="prev" class="btn btn-outline-primary btn-sm" value="Zurück" >Zurück</button> </form> <form action="/calendar/" method="post"> {% csrf_token %} <button name="next" class="btn btn-outline-primary btn-sm" value="Weiter" >Weiter</button> </form> In views.py there are two methods, next_mont() and prev_mont(), that are executed when the designated button is pressed. A fresh instance of the class, which include the methods, monthdays etc happens with click on the calendar-link. def calendar(response): # making class instance if link to calendar is clicked if (response.get_full_path() == '/calendar/') and response.method == 'GET': global cd cd = calendar_dates() cd.set_calendar() #changing months and setting up the dates accordingly (triggered by buttons) if response.method == 'POST': if (response.POST.get('next')): cd.next_month() cd.set_calendar() elif (response.POST.get('prev')): print('prev') cd.prev_month() cd.set_calendar() elif (response.POST.get('current_month')): return HttpResponseRedirect("/calendar") return render(response, 'main/calendar.html', {'cd': cd}) the methods next_month() / … -
How to fix invalid input syntax for type boolean: "abc" in Django and Postgres SQL?
I have a Django models with a duplicate field name trading I didn't noticed at the time I ran makemigration followed by the migrate command (both commands didn't throw any error). As you can see in the model.py below, the name "trading" is used for a BooleanField and a CharField. But now I would like to remove or rename one of them and Django throws an error saying: django.db.utils.DataError: invalid input syntax for type boolean: "future" I'm not familiar with Postgres SQL and have no clue how to solve this problem without destroying and recreating the databse from scratch. class Account(models.Model): exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE, related_name='account', null=True) strategy = models.ForeignKey(Strategy, on_delete=models.CASCADE, related_name='account', null=True) limit_order, credentials, trading = [models.BooleanField(default=True) for i in range(3)] trading = models.CharField(max_length=12, null=True, blank=True, choices=[('future', 'future'), ('swap', 'swap') ]) I've try to first rename the CharField from trading to instrument but in the migration file it looks like Django wants to add a new field. The problem is that everything I modify in my models generate an error. How can I fix this issue while preserving the database? This is the first migration file that generated the error: # Generated by Django 3.0.6 on 2020-07-16 10:11 from … -
AttributeError: 'Settings' object has no attribute 'MEDIA_URL'
So I am practicing an ecommerce website in django and I encountered a problem in rendering the images of the my products. I followed my reference very well and his code worked but mine didnt. These are my references: https://i.stack.imgur.com/PLbkL.png https://i.stack.imgur.com/M3dY6.png My reference worked and got this result: https://i.stack.imgur.com/DSez1.png This is my settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') This is my urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls')), ] urlpatterns += static(settings.MEDIA_URl, document_root=settings.MEDIA_ROOT) And I got this result: AttributeError: 'Settings' object has no attribute 'MEDIA_URl' and my website crashed. Can someone enlighten my stupid tiny brain please? -
How can I publish my django project on cpanel?
How can I publish my django project on cpanel? I want to publish my django project in cpanel -
Override Django MEDIA_ROOT with factory-boy
I'm testing a Django website using pytest and factory-boy. When I test a model with a FileField or ImageField I decorate the test method to override the MEDIA_ROOT setting with a temporary directory so any files created in the test are cleaned up. @pytest.mark.django_db @override_settings(MEDIA_ROOT=tempfile.mkdtemp()) def test_foo(): models.ModelWithFile.objects.create() When I create a model object with factory-boy that uses a FileField the decorator is ignored and a file is created in the original MEDIA_ROOT. @pytest.mark.django_db @override_settings(MEDIA_ROOT=tempfile.mkdtemp()) def test_foo(model_with_file_factory): model_with_file_factory.create() Is there some way I can get factory-boy to use the overrided MEDIA_ROOT? Alternatively is there some way I can get factory-boy to simply always use a temporary directory? -
Django: NoReverseMatch - reverse for '' with arguments '('', '')' not found
I can't figure out what is causing my NoReverseMatch error in django. I've read numerous other questions on SO, and all of the usual suspects do not seem to be a problem in my code. I have defined a namespace in my project urls.py, I've included this in my html template, I've checked my spelling everywhere, and I've made sure that I am passing the right arguments as specified in my apps urls.py. And still it doesn't work! I would be grateful for any help. views.py: from vocab.forms import CustomWordForm @login_required def add_custom_word(request, target_word, source_word): """ Add new word """ if request.method == 'POST': form = CustomWordForm(request.POST) if form.is_valid(): deck_name = form.cleaned_data['deck'] source_word = form.cleaned_data['source_word'] target_word = form.cleaned_data['target_word'] fluency = form.cleaned_data['fluency'] user = request.user Word.objects.create(user=user, target_word=target_word, source_word=source_word, deck_name=deck_name, fluency=fluency) return HttpResponseRedirect(reverse('vocab:index')) if request.method =="GET": from vocab.models import Word user = request.user form = CustomWordForm(initial={'user': user, 'target_word': target_word, 'source_word': source_word, 'deck_name': 'My Words', 'fluency': 0}) return render(request, 'vocab/add_custom_initial.html', {'form': form}) urls.py: app_name='vocab' urlpatterns = [ path("<str:target_word>/<str:source_word>/", views.add_custom_word, name='song-add'), ] html snippet: {% elif item.0 in dict_flash %} <a href="{% url 'vocab:song-add' target_word=item.0 source_word=item.2 %}">Add</a> add_custom_initial.html: <form method="POST" action="{% url 'vocab:song-add' word.target_word word.source_word %}" enctype='multipart/form-data' id="addWordForm"> {% csrf_token %} {% bootstrap_form form …