Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django xhtml2pdf, changing to custom font not working
I'm trying to change the font in my html to pdf project using xhtml2pdf (version 0.2.11) in Django (version 4.2.2). I'm running the project on my Windows 11 Home 22H2, using python 3.11.0 Here is how I try to import the font file html snippet, but the font did not reflect on the page. html snippet @font-face { font-family: Ysabeau Infant; src: url('fonts/Ysabeau-Infant.ttf'); } Views.py def report_rednder_pdf_view(request, *args, **kwargs): pk = kwargs.get('pk') report = get_object_or_404(Report, pk=pk) template_path = 'reports/pdf2.html' context = {'report': report} # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') # If downloadable remove comment #response['Content-Disposition'] = 'attachment; filename="report.pdf"' # If viewable remove comment response['Content-Disposition'] = 'filename="report.pdf"' # find the template and render it. template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF( html, dest=response) # if error then show some funny view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response I tried using the absolute path C:\Users\USER\Desktop\PROJECT\static\fonts\Ysabeau-Infant.ttf instead of the relative path, but that did not work, I get the error: TTFError Exception Value: Can't open file "C:\Users\USER\AppData\Local\Temp\tmpwsd3c9z2.ttf" and from the terminal I get the error, Permission denied: 'C:\Users\USER\AppData\Local\Temp\tmpwsd3c9z2.ttf' I tried running … -
Use user id in bigquery SQL query that is passed into the function via an argument
I'm trying to get the last synced data from bigquery for the given user The query consists of this: mc_query = """ SELECT _fivetran_synced, connector_name FROM `database....` WHERE connector_name = 'pm_' + user.id + '_facebook_pages' """ This is the function below: def facebook_last_pulled(user): # i've tried this code on the line below and replaced user.id with current_user_id in order to make sure the id is in the form of a string as well as using the CAST method on user id in the query #current_user_id = str(user.id) mc_query = """ SELECT _fivetran_synced, connector_name FROM `database....` WHERE connector_name = 'pm_' + user.id + '_facebook_pages' """ print(user.id) last_pulled_data = google_big_query(mc_query) Where I print user.id I get the user id I'm looking for but when I put it into the query I get GenericGBQException, Reason: 400 Unrecognized name: user at [4:45]. So from the seems of it user isn't getting picked up in the variable mc_query, anyone know the reason I'm not getting user in there or a way to solve this? I've tried setting a variable for user.id and using the variable instead of user.id as well as the CAST method in order to change it to a string inside the query. … -
How to add multiple "OR" queries in Django
I have 2 models, Item and Category, the model Item has category field as a foreign key In my views.py I get a list of queries from a POST request queries = ['category1', 'category2', 'category3', ...] I don't know the number of the queries I will get from the request, and I want to filter the Item model based on category field I tried this from django.db.models import Q from .models import Item, Category from django import views class myView(views.View): def post(self, request): queries = request.POST.get('queries', '') if queries: queriesList = [] queries = queries.split(',') # queries = ['category1', 'category2', ....] for query in queries: queriesList.append(Q(category__icontains=query)) queryset = Item.objects.filter(*queriesList) # this will do AND but won't do OR # I tried: queryset = Item.objects.filter([q | Q() for q in queriesList]) but it didn't work Also I tried queryset = Item.objects.filter(category__in=queries) but it's case sensitive -
Refreshing variables shown in a html file by pressing a button
I have a program that takes data from a sensor in my raspberry pi and I want the data taken from the raspberry to be shown in a web page, the idea is that it can be updated every time you press a button that its in the web. I'm right now using django to create the web, but I don't know if it is too much complex for what I'm trying to do. Here I have my data extractor code: import bme280 import smbus2 from time import sleep port = 1 address = 0x76 # Adafruit BME280 address. Other BME280s may be different bus = smbus2.SMBus(port) bme280.load_calibration_params(bus,address) bme280_data = bme280.sample(bus,address) humidity = bme280_data.humidity pressure = bme280_data.pressure ambient_temperature = bme280_data.temperature Here I have the django views.py file: from django.shortcuts import render from django.http import HttpResponse import sys sys.path.append('/home/jordi/weather-station/data') from bme280_sensor import humidity, ambient_temperature, pressure from subprocess import run,PIPE # Create your views here. def home(request): return render(request, 'base.html', {'humitat': humidity, 'temperatura': ambient_temperature, 'pressio': pressure}) def index(request): return HttpResponse("EL temps de vilafant") and finally here I have my html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p>Aqui podras veure el temps de vilafant … -
Python Django API authentication
I am new to Django. I need to use some API to get the .json format data. But the API needs authentication. I have already got the username and password. I see my colleague use Postman to enter the account then he can see the JSON file in intellij. I am in Pycharm, I am wondering is there some code I can use to realize the same function of postman rather than install the postman? What I have: API URL, account username and password Any help is really appreciated, also please let me know which file I should write in the Django, views.py?? Update: thank you for all the help!I am sorry I am not familiar with the postman, I only know my colleague show me how to enter the username and password. I have the API/URL, when I click on it, it will direct me to a page with JSON format data, looks like this {"businessOutcomes":[{"businessOutcomeId":"1234","origin":"JIRA",.....]} I have over 100 this kind of URL/API, I want to get the .json file in pycharm and so I can make them as the df to do the data analysis I want. And my colleague told me that the API has some … -
Cant run gTTS in Django
I am trying to build text to voice app and I had a problem with gTTS. the code I try views.py from django.shortcuts import render from gtts import gTTS from django import forms textfortts = [] class UploadFileForm(forms.Form): tts = forms.CharField(label= " convert text to audio here") def text_to_voice(request): if request.method == "POST" : form = UploadFileForm(request.POST) if form.is_valid(): tts = form.cleaned_data["tts"] textfortts.append(tts) obj = say(language='en-us', text= textfortts) return render(request, "text_to_voice_main.html",{ "form": UploadFileForm(), "lang": "en-us", "text": "text to say", }) text_to_voice_main.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Text to voice</title> </head> <body> <form action=""> {% csrf_token %} <audio src="{% say lang text %}" controls {% load gTTS %} ></audio> {{form}} <input type="submit"> </form> </body> </html> I need to have a text to voice converter. can i know what is the probelms and how i can fix it? -
Django forms passing request via get_form_kwargs fails to give form access to self.request.user
Goal I need to make the user accessible to a form for validation (i.e., through self.request.user) Approach Taken I use the get_form_kwargs() function in my view to make the request available to my form (as suggested here: Very similar problem). Problem Despite following the steps outlined in the StackOverflow answer linked above, I'm getting the error 'NoneType' object has no attribute 'user' Code views.py views.py class MemberDetailView(LoginRequiredMixin, generic.DetailView): """View class for member profile page""" model = User context_object_name = 'user' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs,) context['form'] = JoinCommunityForm() return context class JoinCommunityFormView(FormView): """View class for join code for users to join communities""" form_class = JoinCommunityForm def get_form_kwargs(self, *args, **kwargs): form_kwargs = super().get_form_kwargs(*args, **kwargs) form_kwargs['request'] = self.request return form_kwargs def post(self, request, *args, **kwargs): """posts the request to join community only if user is logged in""" if not request.user.is_authenticated: return HttpResponseForbidden return super().post(request, *args, **kwargs) class MemberDashboardView(View): """View class to bring together the MemberDetailView and the JoinCommunityFormView""" def get(self, request, *args, **kwargs): view = MemberDetailView.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = JoinCommunityFormView.as_view() form = JoinCommunityForm(request.POST) if form.is_valid(): forms.py forms.py from communities.models import Community, UserRoleWithinCommunity class JoinCommunityForm(forms.Form): pin = forms.RegexField('^[A-HJ-NP-Z1-9]$', max_length=6, label='', widget=forms.TextInput(attrs={'oninput': 'this.value = this.value.toUpperCase()'})) … -
Getting error : django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username || I'm a beginner trying to save in Djnago
I'm trying to learn django. Just started with a project. It has 2 applications so far. Employee poll I'm trying to do it via CMD. It shows the following issues. Actually I was trying to follow a tutorial for a django project. I checked, there is no UNIQUE keyword used in the code. I even tried deleting and then saving but didn't resolve. Employee :-- **models.py (employee) : ** from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) designation = models.CharField(max_length=20, null=False, blank=False) salary = models.IntegerField(null=True,blank=True) class Meta: ordering = ('-salary',) #minus sign indicates that we need the result in decending order def __str__(self): return "{0} {1}". format(self.user.first_name, self.user.last_name) @receiver(post_save, sender=User) def user_is_created(sender, instance, created, **kwargs): if created: Profile.object.create (user=instance.) else: instance.profile.save() Poll :-- **models.py (poll)** from django.db import models from django.contrib.auth.models import User # Create your models here.` `class Question(models.Model): # models.Model is the base model. we just need to extend it. #All the class varibales will be considered as the columns of the table. title = models.TextField(null=True, blank = True) status = models.CharField(default = 'inactive', max_length=10) #if we don't pass … -
use django-filters on a queryset in the backend
Assuming I have a queryset and some filters I got from the front end, can I use the pre-defined FilterSet to filter over the queryset? example: models.py class User(models.Model): name = models.CharField(...) score = models.IntegerField(...) filters.py class UserFilter(django_filters.FilterSet): q = django_filters.CharFilter(method="text_search_filter") score_min = django_filters.NumberFilter(field_name="score", lookup_expr="gte") score_max = django_filters.NumberFilter(field_name="score", lookup_expr="lte") class Meta: model = User fields = {} def text_search_filter(self, queryset, name, value): return queryset.filter(name__icontains=value) views.py class UserView(View): filter_class = UserFilter ... def post(self, request, **kwargs): qs = User.object.all() filters = {"q": "john doe", "score_min": 5, "score_max": 10} Can I call UserFilter and pass the filter dict? To prevent me applying those filters again, since I already have those defined in the UserFilter Here's what I tried and didn't work: views.py def post(self, request, **kwargs): qs = User.object.all() filters = {"q": "john doe", "score_min": 5, "score_max": 10} filter = UserFilter(request.GET, queryset=qs) filter.is_valid() qs = filter.filter_queryset(qs) # Did not apply the filters -
Flutter Failed to detect image file format using the file header. Image source: encoded image bytes
I have a django server that has media served by nginx, I'm trying to load the media into my flutter app: Image.network( valueOrDefault<String>( FFAppState().user.photo, 'https://stpeterlibrary.crabdance.com/static/images/LOGO%201.png', ) The static images from the same site load just fine but the network images don't load at all, and give me this error: Failed to detect image file format using the file header. File header was [0x3c 0x21 0x44 0x4f 0x43 0x54 0x59 0x50 0x45 0x20]. Image source: encoded image bytes the static file at images/LOGO%201.png is shown before the page loads the photos, then if the photo is null it shows the same error even though it was working. I think the error is related to the widget that is loading the image Padding( padding: EdgeInsetsDirectional.fromSTEB(16.0, 16.0, 16.0, 16.0), child: InkWell( splashColor: Colors.transparent, focusColor: Colors.transparent, hoverColor: Colors.transparent, highlightColor: Colors.transparent, onTap: () async { await Navigator.push( context, PageTransition( type: PageTransitionType.fade, child: FlutterFlowExpandedImageView( image: Image.network( valueOrDefault<String>( FFAppState().user.photo, 'https://stpeterlibrary.crabdance.com/static/images/LOGO%201.png', ), fit: BoxFit.contain, ), allowRotation: false, tag: valueOrDefault<String>( FFAppState().user.photo, 'https://stpeterlibrary.crabdance.com/static/images/LOGO%201.png', ), useHeroAnimation: true, ), ), ); }, child: Hero( tag: valueOrDefault<String>( FFAppState().user.photo, 'https://stpeterlibrary.crabdance.com/static/images/LOGO%201.png', ), transitionOnUserGestures: true, child: ClipRRect( borderRadius: BorderRadius.circular(12.0), child: Image.network( valueOrDefault<String>( FFAppState().user.photo, 'https://stpeterlibrary.crabdance.com/static/images/LOGO%201.png', ), width: MediaQuery.of(context).size.width * 1.0, height: 230.0, fit: BoxFit.contain, ), ), ), … -
How to connect my EXPO GO app in IOS to my django server? (both running on wsl)
I'm doing a project using React Native/EXPO and Django. It's not my first time using Django, but it's my first time working on mobile development. I have both of my repositories in WSL, but I can't find a way to consume an API from Django Server when I run the app on my Iphone (after reading the QR Code). I always get the same error:[AxiosError: timeout exceeded]. But if I try to consume this API with the WSL ip in postman, it works perfectly. I know that it's an IP/Port problem, but I don't know how to solve it. I would really appreciate some help here. Django Server Settings.py ALLOWED_HOSTS = ["*"] CORS_ALLOW_ALL_ORIGINS = True React-native code login.tsx const handleLogin = async () => { const networkState = await Network.getNetworkStateAsync(); console.log(networkState); const ipAddress = await Network.getIpAddressAsync(); console.log('Endereço IP:', ipAddress); try { const response = await axios.post('http://172.29.160.117:8000/api/token/', { email: email, password: password, }); const accessToken = response.data.access; // Salve o token de acesso no aplicativo (por exemplo, no AsyncStorage) console.log("Resposta do servidor: " + accessToken); // navigation.navigate('ScreenHome'); } catch (error) { console.log(error); } console.log("Finalizou função"); }; Terminal Output -
while implementing django-defender, Error (if response.get("X-Frame-Options") is not None: AttributeError: 'function' object has no attribute 'get')
Implementing a django-defender in web application causing an error while adding a syntax @watch_login in views.py /views.py from defender.decorators import watch_login ...`` @watch_login # error caused due to... def login_user(request): ... return render(request, 'login.html') Error- Internal Server Error: /login Traceback (most recent call last): File "/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/.local/lib/python3.8/site-packages/django/utils/deprecation.py", line 136, in __call__ response = self.process_response(request, response) File "/.local/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'function' object has no attribute 'get' [28/Jun/2023 11:40:18] "GET /login HTTP/1.1" 500 62726 Any solution for it... ThankYou -
xhtml2pdf keep-with-previous.within-page
I'm using the xhtml2pdf library in Django 3.x. I don't know how to make the style work in the template, and still transfer text that is too long to the next page, but only its further part. I'm currently using this code snippet, the rest of the text is moved to the next page, but the styles don't work: <xsl:attribute name="keep-with-previous.within-page"> <tr> <th class="col332"> {{ instance.myvar|linebreaks }} </th> </tr> </xsl:attribute> -
Please I don't understand why my code keeps misbehaving [closed]
The profileimg attribute doesn't seem to work right. class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(blank=True) profileimg = models.ImageField(upload_to='profile_images', default='media/default_img.png') location = models.CharField(max_length=100, blank=True) I've tried using an IF block <div class="col-span-2"> <label for="profile">Profile Image</label> {% if user_profile.profileimg %} <img src="{{ user_profile.profileimg.url }}" width="100" height="100" alt="profile image" /> {% endif %} <input type="file" name="profile_img" class="shadow-none bg-gray-100"> </div> -
Imagine dont display in html page (Django) [closed]
In html file <img src="{% static 'images/welcome-left.png' %}"> this in settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, '/static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "todoapp/static/"), ] maybe error in paths -
Cannot debug app views in DJANGO project using VSCode
I have created an application using the DJANGO framework to create several API programs. To do this I created an app that is now in the installed list of apps. I can debug the manage.py file as the server starts up. But I cannot debug subsequent calls to views in apps, the views.py breakpoints are never hit? However, this is never reached This is what my launch JSON looks like: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "runserver", "--noreload" ], "env": { "DJANGO_SETTINGS_MODULE": "django-sql-project.settings" }, "django": true, "justMyCode": true } ] } and my VS Settings json looks like this: { "python.defaultInterpreterPath":"~//env//Scripts//python.exe", "python.terminal.activateEnvironment": true, "appService.zipIgnorePattern": [ "__pycache__{,/**}", "*.py[cod]", "*$py.class", ".Python{,/**}", "build{,/**}", "develop-eggs{,/**}", "dist{,/**}", "downloads{,/**}", "eggs{,/**}", ".eggs{,/**}", "lib{,/**}", "lib64{,/**}", "parts{,/**}", "sdist{,/**}", "var{,/**}", "wheels{,/**}", "share/python-wheels{,/**}", "*.egg-info{,/**}", ".installed.cfg", "*.egg", "MANIFEST", ".env{,/**}", ".venv{,/**}", "env{,/**}", "venv{,/**}", "ENV{,/**}", "env.bak{,/**}", "venv.bak{,/**}", ".vscode{,/**}" ] } -
How to handle scaling down ECS containers when a Celery worker completes a task?
How can I handle scale-down policies properly when using SQS as a broker and celery with celery beat for task scheduling in a Django app? I have successfully created a scale-up policy that adds new containers when there is a new message in SQS. However, I am facing challenges in implementing a scale-down autoscaling policy. When I choose the "NumberOfMessagesSent" metric for scale-down, it removes tasks before the worker finishes their job. This becomes problematic especially with long-running tasks that can last for several hours. My goal is to ensure that if a celery task's status is "STARTED," the worker responsible for executing the task should be kept alive until the status changes to "SUCCESS" or "FAILURE." How can I achieve this? -
How to group by AND annotate MODELS with django
I have this: class City(models.Model): postal_code = models.IntegerField() class CountryViewset(GenericViewSet, ListModelMixin, RetrieveModelMixin): queryset = City.objects.values("country_code").annotate(cities_ids=ArrayAgg("id")) serializer_class = CountrySerializer class CountrySerializer(serializers.Serializer): country_code = serializers.IntegerField() cities_ids = serializers.ListField(child=serializers.IntegerField()) I got: { country_code: 1, cities_ids: [1, 2, 3], } Is it possible to annotate objects directly ? I want my Country queryset to look like this: <Queryset [ { country_code: 1, cities_ids: <QuerySet [<City: 1>, <City: 2>, <City: 3>]>, }, ... ]> Because for the future I will add a lot of django filters and I don't want to get/filter City objects everytime I do operations for performance purposes. I cannot create Country Model because I'm not allowed to use manage command to sync regularly Country models. -
How to setup redis service with django
I am creating a django CI pipeline using github actions but I am getting the following error. Found 23 test(s). System check identified no issues (0 silenced). EEEEEEEEEEEEs.......... ====================================================================== ERROR: test_account_str (blog.tests.test_models.TestAccount) ---------------------------------------------------------------------- Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.9.17/x64/lib/python3.9/site-packages/redis/connection.py", line 699, in connect sock = self.retry.call_with_retry( File "/opt/hostedtoolcache/Python/3.9.17/x64/lib/python3.9/site-packages/redis/retry.py", line 46, in call_with_retry return do() File "/opt/hostedtoolcache/Python/3.9.17/x64/lib/python3.9/site-packages/redis/connection.py", line 700, in <lambda> lambda: self._connect(), lambda error: self.disconnect(error) File "/opt/hostedtoolcache/Python/3.9.17/x64/lib/python3.9/site-packages/redis/connection.py", line 970, in _connect for res in socket.getaddrinfo( File "/opt/hostedtoolcache/Python/3.9.17/x64/lib/python3.9/socket.py", line 954, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -3] Temporary failure in name resolution My github actions workflow file looks like this services: redis_db: image: redis # env: # CELERY_BROKER_URL: ${{env.CELERY_BROKER_URL}} # CELERY_RESULT_BACKEND: ${{env.CELERY_RESULT_BACKEND}} # REDIS_HOST: localhost # REDIS_PORT: 6379 # ports: # - 6379:6379 options: >- --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 Kindly assist me in identifying the issue. I tried to run the job in a container and directly in the runner but the error still persists -
Change django createAt field
I have this model: class Temp(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) sometimes I want to create an object of this class with a fixed time, but it ignores time and sets times with auto_now_add: data = {'created_at': datetime.datetime.now()} temp = TempSerializer(data=data) what can I do? -
Bug after Stripe payment
I have a website with games. I also included stripe as a payment method, and everything works pretty fine! But, after you finish your payment, you get redirected to your home page, and objects that are looped just DISSAPPEAR! They appear again once you travel from one page to another. Is this a bug in STRIPE or is this something to do with my code? -
Exception Type: NoReverseMatch Exception Value: 'orders' is not a registered namespace
I'm newbie in django and now I'm studiyng by book from Antonio Mele "Django_3_By_Example_Build_powerful_and_reliable_Python_web_applications" I have a question: When I try to pass into cart_detail from the item description page I receive a mistake: Exception Value: 'orders' is not a registered namespace full track below: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/cart/ Django Version: 3.0.14 Python Version: 3.11.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django_extensions', 'django.contrib.contenttypes', 'django.contrib.sessions', 'cart.apps.CartConfig', 'django.contrib.messages', 'django.contrib.staticfiles', 'shop.apps.ShopConfig'\] Installed Middleware: 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'\] Template error: In template C:\\Python\\django-sites\\myshop\\myshop\\shop\\templates\\shop\\base.html, error at line 0 'orders' is not a registered namespace 1 : {% load static %} 2 : \<!DOCTYPE html\> 3 : \<html\> 4 : \<head\> 5 : \<meta charset="utf-8" /\> 6 : \<title\>{% block title %}My shop{% endblock %}\</title\> 7 : \<link href="{% static "css/base.css" %}" rel="stylesheet"\> 8 : \</head\> 9 : \<body\> 10 : \<div id="header"\> Traceback (most recent call last): File "C:\\Python\\django-sites\\myshop\\venv\\Lib\\site-packages\\django\\urls\\base.py", line 72, in reverse extra, resolver = resolver.namespace_dict\[ns\] During handling of the above exception ('orders'), another exception occurred: File "C:\\Python\\django-sites\\myshop\\venv\\Lib\\site-packages\\django\\core\\handlers\\exception.py", line 34, in inner response = get_response(request) File "C:\\Python\\django-sites\\myshop\\venv\\Lib\\site-packages\\django\\core\\handlers\\base.py", line 115, in \_get_response response = self.process_exception_by_middleware(e, request) File "C:\\Python\\django-sites\\myshop\\venv\\Lib\\site-packages\\django\\core\\handlers\\base.py", line 113, in \_get_response response = wrapped_callback(request, \*callback_args, \*\*callback_kwargs) File "C:\\Python\\django-sites\\myshop\\myshop\\cart\\views.py", line 34, … -
Django user update
I want to update User's data, but instead of overwriting the data, it tries to register a new user. How do I make it work? The class looks like this: class SignUpForm(UserCreationForm): email = forms.EmailField(label="", widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Email Address'})) first_name = forms.CharField(label="", max_length=100, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'First Name'})) last_name = forms.CharField(label="", max_length=100, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Last Name'})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['username'].widget.attrs['placeholder'] = 'User Name' self.fields['username'].label = '' self.fields['username'].help_text = '<span class="form-text text-muted"><small>Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</small></span>' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['placeholder'] = 'Password' self.fields['password1'].label = '' self.fields['password1'].help_text = '<ul class="form-text text-muted small"><li>Your password can\'t be too similar to your other personal information.</li><li>Your password must contain at least 8 characters.</li><li>Your password can\'t be a commonly used password.</li><li>Your password can\'t be entirely numeric.</li></ul>' self.fields['password2'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['placeholder'] = 'Confirm Password' self.fields['password2'].label = '' self.fields['password2'].help_text = '<span class="form-text text-muted"><small>Enter the same password as before, for verification.</small></span>' And the views.py part like this: def update_user(request): if request.user.is_authenticated: current_user = User.objects.get(id=request.user.id) profile_user = Profile.objects.get(user__id=request.user.id) # Get Forms user_form = SignUpForm(request.POST or None, request.FILES or None, instance=current_user) profile_form = ProfilePicForm(request.POST or None, request.FILES or None, instance=profile_user) if … -
How to link to a parametrized urlpattern?
I have a parametrized urlpattern path("editpage/<str:title>", views.editpage, name="editpage") How would i go about and provide a link to this in the html? <a href="/editpage/{{ title }}">{{ title }}</a> I dont want something like this, where the link is "hardcoded". Rather i want to use the feature '{% url 'editpage' %}'. But this yields: Reverse for 'editpage' with no arguments not found. But how do i pass in the extra information? I tried '{% url 'editpage' title='{{ title }}' %}', but that doesnt work -
New django dashboard for free
I started a project on kickstarter in which I'm making a dashboard for managing a server in django. I do it in react and django. The panel will be available for free after release. Please support me :) (I know that it's not question) KICKSTARTER