Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deal with double foreign keys in Django while creating an API?
I created these models for my database. It's supposed to be kind of a tree (country>multiple cities>multiple airports). The problem is I want to use autocomplete which would show not only the name of an airport and the name of the city, but also the name of the country. I'm stuck because I don't know how to add the country to my API (together with airports of course). Is there a way to do it or maybe I should change the architecture of my database? class Country(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class City(models.Model): name = models.CharField(max_length=120) country = models.ForeignKey(Country, on_delete=models.CASCADE) def __str__(self): return self.name class Airport(models.Model): name = models.CharField(max_length=150) abbr = models.CharField(max_length=4) city = models.ForeignKey(City, on_delete=models.CASCADE) country = city.country #how can I do this? def __str__(self): return self.name + ' (' + self.abbr + ')' from serializers.py: class AirportSerializer(serializers.ModelSerializer): city = serializers.StringRelatedField() class Meta: model = Airport fields = ['name', 'city'] from views - creating custom search API: class AirportList(generics.ListAPIView): serializer_class =AirportSerializer def get_queryset(self): airport = self.kwargs['airport'] list_airports = Airport.objects.filter(name__icontains = airport) return list_airports Path in case it's helpful: re_path('^airports/(?P<airport>.+)/$', views.AirportList.as_view()), script for autocomplete: <script> new Autocomplete ('#autocomplete', { search: input=>{ console.log(input) const url = `/airports/${input}/` return … -
Python not modifying global variable
i have below code failure = "" def walk(dictItems): returnVal = "" for key, item in dictItems.items(): if isinstance(item,dict): walk(item) else: returnVal = returnVal +"<li>"+key+" : "+ item + "</li>" global failure failure = returnVal walk(dictItems) print(failure) failure variable is always null despite having vaulues on returningVal any help? -
Django, multiple DB hits when repeating one related query
This is the model: class Category(models.Model): name = models.TextField() class Post(models.Model): category = models.ForeignKey(Category) Now, I want to get posts of a category: category = Category.objects.get(id=1) posts = category.post_set.all() # this line hit the DB posts = category.post_set.all() # and this line hit the DB again! How to use the cached result in these relations. I use Django rest-framework and it makes DB hit multiple times for each instance. -
Django Broken pipe-Errno 32 Broken pipe error how can I fix it?
I have multiple coins acceptions page I have in models.py def updatedeposit(self, dp): if dp.coin == Coins.BTC: return self.updatedeposit_btc(dp) elif dp.coin == Coins.XMR: return self.updatedeposit_xmr(dp) elif dp.coin == Coins.LC: return self.updatedeposit_ltc(dp) else: raise WalletException('No such deposit option') def updatedeposit_btc(self, dp): if dp.wallet != self: raise WalletException("Can't update a deposit created by another wallet") if dp.status not in STATUS_TO_UPDATE: return dp try: address = self.bitcoind.validate(dp.recv_address) except: raise WalletException("Invalid BTC address") try: unconf_amount = self.bitcoind.unconf_by_addr(address) conf_amount = self.bitcoind.conf_by_addr(address) except: raise WalletException('Bitcoind error') if unconf_amount > conf_amount: dp.status = Status.UNCONFIRMED dp.sats_amount = unconf_amount dp.save() return dp if conf_amount == 0: delta = timedelta(minutes=settings.DEPOSIT_EXPIRATION) if dp.date < timezone.now() - delta: dp.status = Status.EXPIRED dp.save() return dp delta = timedelta(minutes=settings.DEPOSIT_EXPIRATION+40) if dp.date < timezone.now() - delta: dp.status = Status.CANCELLED dp.save() return dp dp.status = Status.WAITING dp.sats_amount = 0 dp.save() return dp and in bitcoin core settings fille bitcoind.py def create_address(self): return self.proxy.getnewaddress(account=self.ACC) def unconf_by_addr(self, addr): return self.proxy.getreceivedbyaddress(addr, minconf=0) i have succeeded to create new btc address from bitcoin-core wallet in the page but when the page refresh to check if there new transaction coming I get this 2 error first Django Version: 3.2.6 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin.apps.SimpleAdminConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', … -
Page not found error 404 django navbar link
I have an issue with the navbar link where it does find the html page ? my mysite/urls.py """firt_website URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from pages import urls app_name = 'pages' urlpatterns = [ path('', include('pages.urls')), ] my blog/urls.py : from django.contrib import admin from django.urls import path, re_path from . import views app_name = 'main' urlpatterns = [ path('', views.home_page, name='homepage'), path('education/', views.education, name='education'), path('experience/', views.experience, name='experience'), path('portfolio/', views.portfolio, name='portfolio'), ] my navbar.html : <div class="u-custom-menu u-nav-container-collapse"> <div class="u-align-center u-black u-container-style u-inner-container-layout u-opacity u-opacity-95 u-sidenav"> <div class="u-sidenav-overflow"> <div class="u-menu-close"></div> <ul class="u-align-center u-nav u-popupmenu-items u-unstyled u-nav-2"><li class="u-nav-item"><a class="u-button-style u-nav-link" href="Acceuil.html" style="padding: 10px 0px; text-shadow: 0 0 8px rgba(128,128,128,1);">Home</a> </li><li class="u-nav-item"><a class="u-button-style u-nav-link" href="{% url 'main:experience' %}" style="padding: 10px 0px; text-shadow: … -
Customized Login site not showing in Django
I have created a Django App and want to provide a custom Login page with only the possibility to use a Google login. I have implemented the Google login based on this post: https://www.section.io/engineering-education/django-google-oauth/ It actually works fine and when I hit localhost/account/login I am getting a login page: I actually do not want a sign up and a "local" sign in option, I only need a Google login. To achieve this I have created the following folder structure to overwrite the login template (based on https://learndjango.com/tutorials/django-login-and-logout-tutorial): MyApp/templaltes/registration/login.html login.html has the following content: {% extends "base.html" %} {% load i18n %} {% load socialaccount %} {% block content %} <div class="row"> <center><h1>{% trans 'LoginHeading' %}</h1></center> </div> {% if user.is_authenticated %} <p>Welcome, You are logged in as {{ user.username }}</p> {% else %} <a href="{% provider_login_url 'google' %}">Login With Google</a> {% endif %} {% endblock %} I have also added 'DIRS': [str(BASE_DIR.joinpath('templates'))] to the TEMPLATES section in settings.py. Unfortunately I am still seeing the Django default login page. What am I missing? (I have also restarted the dev server to make sure it is not an issue there with the same result) -
Django Bootstrap Modal: CRUD for foreign key model
Models.py: class Dossier(models.Model): name = models.CharField('Name', max_length=200) class Meta: verbose_name = 'Dossier' verbose_name_plural = 'Dossiers' def __str__(self): return self.name class Activity(models.Model): dossier = models.ForeignKey(Dossier, on_delete=models.CASCADE, verbose_name='Dossier') detail = models.CharField('Activity', max_length=1000) topic = models.ForeignKey(Topic, on_delete=models.CASCADE, verbose_name='Topic') source_url = models.CharField('Source URL', max_length=1000, null=True, blank=True) class Meta: verbose_name = 'Activity' verbose_name_plural = 'Activities' def __str__(self): return self.detail Github Repo: username: admin password admin: I'd like to add, edit and delete Activity for a Dossier while editing using Bootstrap-modal asynchronously. I tried to follow this article. urls.py: from django.urls import path from bpsbpoliticaldb import views urlpatterns = [ path('dossiers/edit/<str:pk>/', views.dossier_edit, name="dossier_edit"), path('dossiers/activity/<str:pk>/', views.dossier_activity_create, name="dossier_activity_create"), path('dossiers/activity/add/', views.dossier_activity_add, name="dossier_activity_add"), ] views.py: def dossier_edit(request, pk): dossier = get_object_or_404(Dossier, id=pk) activities = Activity.objects.filter(dossier=dossier) context = {'dossier': dossier, 'activities': activities} return render(request, 'bpsbpoliticaldb/dossier/dossier_edit.html', context) def dossier_activity_create(request, pk): data = dict() if request.method == 'POST': form = ActivityForm(request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True else: data['form_is_valid'] = False else: form = ActivityForm() context = {'form': form} data['html_form'] = render_to_string('bpsbpoliticaldb/activity/partial_activity_create.html', context, request=request, ) return JsonResponse(data) forms.py: from django.forms import ModelForm from django import forms class ActivityForm(ModelForm): class Meta: model = Activity widgets = { 'detail': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}), 'topic': forms.Select(attrs={'class': 'form-control'}), 'source_url': forms.TextInput(attrs={'class': 'form-control'}), } fields = ['detail', 'topic', 'source_url'] … -
Django 2 schedulers being run
These are my files- from django.apps import AppConfig class ApiConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'api' def ready(self): import api.scheduler as scheduler scheduler.start() from apscheduler.schedulers.background import BackgroundScheduler def fetch_new_raw_data(): '''Fetches new data''' def start(): scheduler = BackgroundScheduler() scheduler.add_job(fetch_new_raw_data, 'interval', minutes=1) scheduler.start() fetch_new_raw_data() When using py manage.py runserver django spawns 2 processes, each one will start a scheduler. Is there a way to load up the scheduler only in 1 process and use the same in both or is it ok for them to start their own scheduler? -
ID which consists of slug and uuid Django Rest Framework
I want to identify my database items over id which consists of slug and uuid, so if two users add f.e. name of the item: "Mercedes A40", they will be stored in database with different ids f.e. "mercedes-a40-25b6e133" and "mercedes-a40-11ac4431". What should I type inside my Product model in id field? How can I combine it? id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) slug = models.SlugField(max_length=250, unique_for_date='published') -
How to produce and consume JSON messages between Django services using Redis as a message queue?
I am trying to find a way to enable communication between two Django services using Redis as a message queue. One service would produces JSON data, publish it to the queue and the other one would consume the message. Something similar to what I want to achieve is described here using Spring Boot and RabbitMQ: https://www.javainuse.com/spring/spring-boot-rabbitmq-consume Any articles or suggestions would mean a lot. -
Using a for loop with Mapbox
I want to do what is done in this example: https://docs.mapbox.com/mapbox-gl-js/example/popup-on-hover/ but instead of adding each point manually i want to insert the data from my forms in a for loop. I have been succesful with using for loops to add markers in this format: {% for markers in marker %} {% if markers.PlantName in Bær %} var marker = new mapboxgl.Marker({ color: 'red'}) {% elif markers.PlantName in Frugt %} var marker = new mapboxgl.Marker({ color: 'orange'}) {% else %} var marker = new mapboxgl.Marker({ color: 'green'}) {% endif %} .setLngLat([{{ markers.lon }}, {{ markers.lat }}]) .setPopup(new mapboxgl.Popup().setHTML("<p>{{markers.PlantName}}<p>")) .addTo(map); {% endfor %} But in the example they add the points differently. Thanks in advance! -
django-import-export: Import many to many field
I have a model "Website", which can have multiple categories: Model.py class Website(models.Model): ... uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) category = models.ManyToManyField('Category', related_name='website_category') country = models.ForeignKey('Country', null=True, blank=False, on_delete=models.SET_NULL, related_name='website_country') language = models.ForeignKey('Language', null=True, blank=False, on_delete=models.SET_NULL, related_name='website_language') ... I'm willing to import multiple, comma separated, categories for each website via xlsx file. Following is my admin file: Admin.py class WebsiteResource(resources.ModelResource): category = fields.Field( column_name='category', attribute='category', widget=ManyToManyWidget(Category, ',', 'name')) country = fields.Field( column_name='country', attribute='country', widget=ForeignKeyWidget(Country, 'name')) language = fields.Field( column_name='language', attribute='language', widget=ForeignKeyWidget(Language, 'name')) def before_import_row(self, row, row_number=None, **kwargs): try: row['uuid'] = uuid.uuid4() row['cost_price'] = row['publication_price'] * (row['percentage']/100) row['url'] = clear_url(row['url']) row['outreached_by'] = get_outreached_by_details(kwargs['user']) except Exception as e: raise ValidationError(e) class Meta: model = Website import_id_fields = ['uuid'] fields = (....) class WebsiteAdmin(ImportMixin, admin.ModelAdmin): resource_class = WebsiteResource .... def get_import_formats(self): formats = ( # base_formats.CSV, base_formats.XLSX, ) return [f for f in formats if f().can_export()] class meta: model = Website Everything else if working smoothly but since this category field is a many to many field so I have an exception when I confirm import. Exception: insert or update on table "GPFY_website_category" violates foreign key constraint "GPFY_website_category_website_id_32320ddd_fk_GPFY_website_uuid" DETAIL: Key (website_id)=(3ed6ae85-d309-4e7f-b2d9-5a74ddeb3b90) is not present in table "GPFY_website". Maybe this is because when an … -
Django password_change_done not found
I have a small application that I'm writing, but I have came into some trouble with the password changing elements used with the Django authentication framework. But I always get the error after changing a password that: Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. Here is my code below: #account urls.py from django.urls import path, include from django.contrib.auth import views as auth_views from . import views app_name = 'account' urlpatterns = [ #Password Changes URLs path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), ] This is my directory structure for the login system: Directory Structure Here's the password_change.html file: <h3 style="text-align: center;">Change your password</h3> <div class="login-form" style="text-align: center; "> <form method="post"> {{ form.as_p }} <p><input type="submit" value="Change"></p> {% csrf_token %} </form> </div> Any help would be greatly appreciated! -
django filter can't find a right solution
my models: class Order(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="order_user") first_name = models.CharField(_('first name'), max_length=50) last_name = models.CharField(_('last name'), max_length=50) email = models.EmailField(_('e-mail')) address = models.CharField(_('address'), max_length=250) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) # objects = models.Manager() # default manager ord_obj = ManagerOrder() # custom manager class OrderItem(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) shop = models.ForeignKey(MyShop, related_name='shop_order', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) # objects = models.Manager() # default manager items_obj = ManagerOrderItem() # custom manager my views: def shop_orders(request): order = Order.ord_obj.filter(items__shop=request.user.user_profile_shop) return render(request, 'account/paneli/shop/orders/shop_orders.html', {'order': order,}) in the template,it show the order of the shop but it shows the OrderItem of all the shops {% for order in order %} order.id #it ok {% for item in order %} {{ item.product }}# wrong shows the OrderItem of all the shops {% endfor %} {% endfor %} can you help me someone where i went wrong -
While testing django web app in using waitress, it serve on http://0.0.0.0:8000
While I use the url http://0.0.0.0:8000 in browser, it says "The site cannot be reached." How to solve this problem. Any one help me, please! my django project name is: testdj and I use command -> waitress-serve --port=8000 testdj.wsgi:application -
How to create a rest api with nested url in a DRY fashion?
I am trying to write a simple Geocache application. The backend access should work as follows: One Geocache Object contains general information (like creation date or difficulty level) but also several instructions, which have a fixed order (example instruction: Go first to coordinate lon/lat). The general URL structure is example.com/geocache/ List view for geocaches (get) example.com/geocache/<geocache_pk>/ Detail view for geocache (get/post/put/delete) (all instructions should be collectively displayed here but they cannot be manipulated here) example.com/geocache/<geocache_pk>/instruction/ Only to create new instructions (post) example.com/geocache/<geocache_pk>/instruction/<instruction_position/> Only for instruction manipulation/deletion (put/delete) I tried to accomplish this structure through custom actions with regular expressions in the url_path but I feel it is not DRY enough. I am learning Django only for a few days so I might be missing some sophisticated patterns. Please also let me know if the general approach makes sense to you. Thank you for your effort! I really appreciate any suggestions to get better. models.py from django.db import models from django.db.models import F from django.db.models.signals import pre_save, post_delete from django.dispatch import receiver from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ class Geocache(models.Model): class DifficultyLevel(models.TextChoices): BEGINNER = 1, _('Beginner') INTERMEDIATE = 2, _('Intermediate') ADVANCED = 3, _('Advanced') user_created = models.ForeignKey(User, … -
DJANGO - Trying to set up a dependent dropdown list
As you can understand I'm new to cooking, but I can't find where my code is wrong. Struggling for full day now, replacing and renaming the different . Perhaps some fresch eyes will spot the misstake I've made. Something in my code generates none "issue areas". What I want to do. When you on a workorder select product so will it limit the issue areas you can define. -----models.py------ class Products(models.Model): m_product_short=models.CharField(unique=True,max_length=5) m_product_long=models.CharField(max_length=40) def __str__(self): return self.m_product_short class IssueAreas(models.Model): product=models.ForeignKey(Products, on_delete=models.SET_NULL, null=True) m_issue=models.CharField(max_length=50) def __str__(self): return self.m_issue class WorkOrder_main(models.Model): wo_machine_product = models.ForeignKey(Products, on_delete=models.SET_NULL, null=True) wo_issue_area = models.ForeignKey(IssueAreas,on_delete=models.SET_NULL, null=True) ----url.py----- urlpatterns = [ path("create/",views.WO_CreateView.as_view(), name="Create Order"), path('ajax/loadIssue/', views.loadIssueAreas, name='ajax_loadIssueAreas'), # AJAX ] ----views.py----- class WO_CreateView(CreateView): template_name = 'WorkOrderCreate.html' model = WorkOrder_main form_class = WorkOrder_Add2 # AJAX def loadIssueAreas(request): product_id = request.GET.get('wo_machine_product') issues = IssueAreas.objects.filter(product_id=product_id).all() return render(request, 'oa/IssueAreaDropDown.html', {'issues': issues}) ----forms.py----- class WorkOrder_Add2(forms.ModelForm): class Meta: model=WorkOrder_main fields= ' __all__ ' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['wo_issue_area'].queryset = IssueAreas.objects.none() if 'product' in self.data: try: product_id = int(self.data.get('product')) self.fields['wo_issue_area'].queryset =IssueAreas.objects.filter(product_id=product_id).order_by('id') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['wo_issue_area'].queryset = self.instance.product.IssueAreas_set.order_by('id') ----WorkOrderCreate.html---- <!DOCTYPE html> <html lang="en"> <meta charset="UTF-8"> {% extends "Master.html" %} {% block title %}Create{% endblock %} {% block content %} <h1>Create Order</h1> <form … -
Is it possible to send data as a hyper-link?
I want to send data like this Here is my code if request.method == 'GET': context = [] context.append({ link':"<a href=\"www.google.com\">click me</a>", }) return Response(context, status=status.HTTP_200_OK) and this is the result -
django mssql password not being acknowledged
The official error is "argument of type 'NoneType' is not iterable" Doing some digging I notice that mssql sees 'PASSWORD' as None, even though it is defined in settings (os.environ.get('DBPW')) Doing os.environ.get('DBPW') in python3 manage.py shell gives me the correct password, and doing settings.DATABASES['default'] in shell shows the correct password as well, so I know it's some sort of glitch in mssql. Here are my settings: DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': 'tc_django_dev', 'USER': 'SA', 'PASSWORD': os.environ.get('DBPW'), 'HOST': 'localhost', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } Here is what (python) mssql says it has: conn_params: {'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'ENGINE': 'mssql', 'HOST': 'localhost', 'NAME': 'tc_django', 'OPTIONS': {'driver': 'ODBC Driver 17 for SQL Server'}, 'PASSWORD': None, 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': None}, 'TIME_ZONE': None, 'USER': 'SA'} Help. -
Different selection dropdown for different products using Django
I am building a webshop for a school project and would like to add a dropdown with color options for some products (catears), and for other products (quipu) I would like to provide the customer with two dropdowns and a text fiels where they can enter a name/work to make their order custom. So I'm thinking something like this in the html: <p class="mt-3">{{ product.description }}</p> <form class="form" action="{% url 'add_to_bag' product.id %}" method="POST"> {% csrf_token %} <div class="form-row"> {% if catears_has_colors %} {% include 'products/includes/catears_has_colors.html' %} {% elif qupiu_custom_form %} {% include 'products/includes/qupiu_custom_form.html' %} {% endif %} Quipu_custom_form looks like this, catears_has_colors is simular: <div class="quipu-form-control" name="quipu_color_choise" id="id_quipu_color_choise"> <p>Write the name/word you would like (max 12 letters), and pick what color and type of stone pearl you prefer</p> <div class="col-12 col-md-6"> <select class="form-control rounded-0 w-50"> <option value="pearl_white" selected>Pearl White</option> <option value="light_blue">Light Blue</option> </select> </div> <div class="col-12 col-md-6"> <select class="form-control rounded-0 w-50"> <option value="labradorite" selected>Labradorite</option> <option value="amethyst">Amethyst</option> </select> </div> <div class="col-12"> <input type="text" name="quipu_custom_name" id="id_quipu_custom_name" > </div> </div> And in the products/models.py I got these classes: class CatEarColor(models.Model): BLUE = 'BL' PINK = 'PN' CATEAR_COLOR = [ (BLUE, 'blue'), (PINK, 'pink'), ] catear_color = models.CharField( max_length=2, choices=CATEAR_COLOR, default=BLUE ) def … -
getting radio button value in views.py from template
how can i access of the selected button from my template in my views.py <form action="{% url 'user_vote' q.pk %}" method="POST"> {% csrf_token %} {% for choix in q.choice_set.all %} {% if forloop.counter == 1 %} <input type="radio" name="choix" id="{{ choix.pk }}" required/> <label for="{{ choix.pk }}"> {{ choix.choice_text }} - {{ choix.total }}</label> <br> {% else %} <input type="radio" name="choix" id="{{ choix.pk }}" value="{{ choix.pk }}"/> <label for="{{ choix.pk }}"> {{ choix.choice_text }} - {{ choix.total }}</label> <br> {% endif %} {% endfor %} <button type="submit" class="btn btn-primary">Votez</button> </form> views.py: @login_required def user_vote(request,question_id): question = get_object_or_404(Question,pk=question_id) if request.method == 'POST': vote =request.POST.get("choix") print(vote) #i am getting 'on' messages.success(request, "Votre vote a été crée." ) return HttpResponseRedirect(reverse('show_community',kwargs={'pk':question.communaute_id})) else: return redirect('news') my problem is i am not getting the value of the select radio button i am getting 'on' on the server side.i tried many answers from stackoverflow here but none helped me.thanks -
Reverse for 'X' not found. 'X' is not a valid view function or pattern name. Django Framework
I 'm new to Django concept I have 3 files for this issue. I have a urls.py in my project file call firt_website with the following code: """firt_website URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from pages import urls app_name = 'main' urlpatterns = [ path('', include('pages.urls', namespace='home')), path('portfolio/', include('pages.urls', namespace='portfolio')), path('experience/', include('pages.urls', namespace='experience')), path('education/', include('pages.urls', namespace='education')), ] I have the Navbar HTML that will be included in an index page HTML as {% extends 'navbar.html' %} : the files contains : <div class="u-custom-menu u-nav-container"> <ul class="u-custom-font u-font-titillium-web u-nav u-spacing-30 u-unstyled u-nav-1"><li class="u-nav-item"><a class="u-border-2 u-border-active-white u-border-hover-custom-color-2 u-border-no-left u-border-no-right u-border-no-top u-button-style u-nav-link u-text-active-white u-text-hover-custom-color-2 u-text-white" href="Acceuil.html" style="padding: 10px 0px; text-shadow: 0 0 8px rgba(128,128,128,1);">Home</a> </li><li class="u-nav-item"><a class="u-border-2 u-border-active-white u-border-hover-custom-color-2 u-border-no-left u-border-no-right u-border-no-top u-button-style … -
how to avoid assignment If one value is set on django model field?
I have a product model with 2 foreign keys to models percentDiscount and cashDiscount, I want to apply just one of these discounts on my unit price. So i defined a final_price property to get the final_price of item. but i want to apply one of these discount on item at the moment. There are 2 ways, 1) when one of discount set, do not let another to be set and set it as none. 2) do some thing in final price to set just one of these discount. Below is my code, I will be happy if you help me to make the best decision. class Product(models.Model): class Meta: verbose_name = 'محصول' verbose_name_plural = 'محصولات' ordering = ('created_at',) name = models.CharField(max_length=50) category = models.ForeignKey('product.Category', on_delete=models.CASCADE, related_name='products') brand = models.ForeignKey('product.Brand', on_delete=models.CASCADE, related_name='products') # labels such as bestseller, new, not available, etc ... label = models.CharField(choices=LABEL, max_length=1) image = models.ImageField(upload_to='product/static/product/images/', null=True, blank=True) description = models.TextField(max_length=1000, null=True, blank=True) is_original = models.BooleanField() inventory = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) unit_price = models.DecimalField(max_digits=8, decimal_places=2) number_sold = models.PositiveIntegerField() # discount code for this book cash_code = models.ForeignKey('cart.CashDiscount', null=True, on_delete=models.CASCADE, blank=True, related_name='related_products') percentage_code = models.ForeignKey('cart.PercentageDiscount', null=True, on_delete=models.CASCADE, related_name='related_products', blank=True) # for food … -
Django : File object is not Json serializable
I want to send back a file as a response to my post request but i get this error file object is not json serializable , so how do i send a file back as a response for my post request : @api_view(['GET', 'POST']) def Upload_list(request): if request.method == 'GET': queryset = Uploads.objects.all() uploads=queryset.filter(owner=request.user) serializer = UploadSerializer(uploads, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = UploadSerializer(data=request.data) if serializer.is_valid(): serializer.save(owner=request.user) respFile=list(File.objects.filter(id=str(File.objects.latest('created_at')))) return Response(respFile) #return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Running MYSQL command inside a shell script not working
I am trying to run a shell script with commands to run the Django Server. #!/bin/bash docker run -e MYSQL_ROOT_PASSWORD=root --name db_name -d mariadb docker exec -it container_name mysql -u root -proot -e "create database db_name CHARACTER SET UTF8; CREATE USER invuser@XXX.17.0.3 IDENTIFIED BY 'root1234$'; GRANT ALL PRIVILEGES ON db_name .* TO invuser@XXX.17.0.3 IDENTIFIED BY 'root1234$';" #mysql -u root -proot -e "create database db_name CHARACTER SET UTF8; CREATE USER invuser@XXX.17.0.3 IDENTIFIED BY 'root1234$'; GRANT ALL PRIVILEGES ON db_name .* TO invuser@XXX.17.0.3 IDENTIFIED BY 'root1234$'" echo "Docker image name will be $1" python3 manage.py makemigrations python3 manage.py migrate docker build . -t $1 docker run -d -p 8000:8000 $1 In this script, When I am trying to run : docker exec -it container_name mysql -u root -proot -e "create database db_name CHARACTER SET UTF8; CREATE USER invuser@XXX.17.0.3 IDENTIFIED BY 'root1234$'; GRANT ALL PRIVILEGES ON db_name .* TO invuser@XXX.17.0.3 IDENTIFIED BY 'root1234$';" I am getting this error : ERROR 2002 (HY000): Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2) OR when I run : mysql -u root -proot -e "create database db_name CHARACTER SET UTF8; CREATE USER invuser@XXX.17.0.3 IDENTIFIED BY 'root1234$'; GRANT ALL PRIVILEGES ON db_name .* TO invuser@XXX.17.0.3 IDENTIFIED BY …