Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Payment options with Django
I am trying to make a real time e-commerce site that people can really order stuff on. I wanted it to have an actual payment option like Stripe. But is there any other option other than Stripe? Can I use something like Payoneer, or PayPal or something like that? -
Django form add initial data to bound form
I am trying to add initial data from 1 form into the second form but I cannot seem to get it work. I've tried different methods but the closest I got came from this post Here is my code if request.method == 'POST': laptop_select_form = LaptopSelectForm(request.POST) if laptop_select_form.is_valid(): laptop_model_id = literal_eval(laptop_select_form.cleaned_data['model'])[0] laptop_for_parts_form = LaptopForPartsForm(request.POST, laptop_id=laptop_model_id) if laptop_for_parts_form.is_valid(): else: laptop_select_form = LaptopSelectForm() laptop_for_parts_form = LaptopForPartsForm() And the form class LaptopForPartsForm(forms.ModelForm): def __init__(self, laptop_id=0, *args, **kwargs): super(LaptopForPartsForm, self).__init__(*args, **kwargs) self.laptop_id = laptop_id class Meta: model = LaptopForParts fields = ('__all__') widgets={'laptop_id': forms.HiddenInput()} But I keep getting this error: laptop_for_parts_form = LaptopForPartsForm(request.POST, laptop_id=laptop_model_id) TypeError: __init__() got multiple values for argument 'laptop_id' Can someone more experienced please point me in the right direction? -
Not entering to the delete function [closed]
Here my modelserializer here my delete function note working not entering to the delete function def destroy(self,validated_data): gameevent = validated_data.get('gameevent') match_round =validated_data.get('match_round') match = Matchscore.objects.filter(gameevent=gameevent,match_round=max(match_round)) if match : match.delete() return response("success") else: raise serializers.ValidationError("Can't delete this round") -
I want to create a details page with two models for an auction site with django but keep getting FieldError. How do I correct this error?
I am creating an ebay like aunction site, the details view page should reflect details from two models. One of the models has the details of the current_bid (this is created when creating the listing), there is also the second model that contains new_bids (this is where the users who want to purchase the item can input their bids). The issue(s) I'm having is how to put two models in my details view and also if you can confirm my current logic in finding out the highest bid (if this is correct or not). MODELS.PY class Auction(models.Model): ABSTRACT = 'AB' MODERN = 'MN' ILLUSTRATION = 'IN' select_category = [ ('ABSTRACT', 'Abstract'), ('MODERN', 'Modern'), ('ILLUSTRATION', 'Illustration') ] title = models.CharField(max_length=25) description = models.TextField() current_bid = models.IntegerField(null=False, blank=False) image_url = models.URLField(verbose_name="URL", max_length=255, unique=True, null=True, blank=True) category = models.CharField( choices=select_category, max_length=12, default=MODERN, null=True, blank=True ) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ['-created_at'] class Bids(models.Model): auction = models.ForeignKey(Auction, on_delete=models.CASCADE, related_name='bidding') user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='bidding') new_bid = models.DecimalField(max_digits=8, decimal_places=2) # new_bid = MoneyField(max_digits=10, decimal_places=2, null=False, blank=False, default_currency='USD', default=0) done_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['auction', '-new_bid'] FORMS.PY class AuctionForm(forms.ModelForm): class Meta: model = Auction fields = ['title', 'description', … -
pip install mysqlclient issues
when I try to use pip install mysqlclient issues command I get this error Collecting mysqlclient Using cached mysqlclient-2.1.0.tar.gz (87 kB) Preparing metadata (setup.py) ... done Collecting issues Downloading issues-0.0.0.tar.gz (858 bytes) Preparing metadata (setup.py) ... doneBuilding wheels for collected packages: mysqlclient, issues Building wheel for mysqlclient (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [42 lines of output] error: command '/opt/rh/devtoolset-7/root/usr/bin/gcc' failed: No such file or directory [end of output] -
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_HOST_USER
I've been trying to set up a contact form for my website and the form seems to go through ok but no email is actually sent. I then tried to debug by printing the EMAIL_HOST_USER in a test.py file from the command line and ran into this error which makes me think the variable isn't being passed from my local_settings.py Full Traceback call File "/Users/temporaryadmin/DCI_Projects/Portfolio/test.py", line 4, in <module> print(settings.EMAIL_HOST_USER) File "/Users/temporaryadmin/DCI_Projects/Portfolio/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 84, in __getattr__ self._setup(name) File "/Users/temporaryadmin/DCI_Projects/Portfolio/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 65, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_HOST_USER, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Any help would be appreciated, thanks. -
how to add django url and function in vue js code
I have a drf view to download the file i dont have knowledge on how to add the url in vue js here is how my code looks like views.py @api_view(('GET',)) def my_view(request,pk): data = get_object_or_404(Mymodel,pk) response = HttpResponse( data.data_file, content_type='', ) return response model.py class Mymodel(models.Model): datafile = models.FileField(upload_to='',blank=True) urls.py path('myurl/<int:pk>/',views.my_view,name='url_download') vue.js downloaddatafile: function (id) { alert('TODO: add URL & function to download datafile, file id: ' + id); }, -
I can not find the solution when it comes to CRISPY FORMS
IN MY DJANGO PROJECT I AM GETTING THIS EXCEPTION File "", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'crispy_formsmyapp -
Django. How to get profile picture url google Oauth2 api
how can I get a google profile picture with Oauth2 authorization settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'djoser', 'accounts.apps.AccountsConfig', 'social_django', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist', 'blog' ] SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'openid'] SOCIAL_AUTH_GOOGLE_OAUTH2_EXTRA_DATA = ['first_name', 'last_name', 'fullname', 'username', 'picture'] models.py class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) picture = models.URLField(blank=True) fullname = models.CharField(max_length=100) username = models.CharField(max_length=100) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'fullname', 'picture', 'username'] returns all fields except picture during authorization -
How to save a model field having many to many realtionship with another model so that it will update the value automatically on another model?
I am having a model name 'tag' which has field name talent which has many to many relationship field with model name 'talent'. now I want to update the talent field and save it and it should update the talent model's tag field. I'm new in django. Please help me to find the solution for it. here's the code: tag.py from django.db import models from django.utils.translation import gettext as _ from fotoleybend.mixin import ( IsActiveAndVerifiedMixin, PrimaryKeyMixin, TimeStampMixin, ) from talent.models.talent import Talent class Tag(PrimaryKeyMixin, TimeStampMixin, IsActiveAndVerifiedMixin): """Tag model""" tag = models.CharField(unique=True, max_length=105, db_index=True) talents = models.ManyToManyField( "talent.Talent", blank=True, verbose_name=_("Tag Talents"), related_name="tag_talents", ) class Meta: ordering = ["tag"] def __str__(self): return self.tag talent.py from django.db import models from django.utils.translation import gettext as _ from fotoleybend.mixin import ( IsActiveAndVerifiedMixin, PrimaryKeyMixin, TimeStampMixin, ) class Talent(PrimaryKeyMixin, TimeStampMixin, IsActiveAndVerifiedMixin): """Talent model""" talent = models.CharField(unique=True, max_length=155, db_index=True) is_primary = models.BooleanField( verbose_name=_("Primary"), default=True, db_index=True ) tags = models.ManyToManyField( "talent.Tag", blank=True, verbose_name=_("Talent Tags"), related_name="talent_tags", ) class Meta: ordering = ["talent", "is_primary"] def __str__(self): return self.talent -
Django database modeling
I have a scenerio for which im trying to create the database models but I'm not able to find a perfect way to do it Scenerio is as follows . let's say there is a company which gives offer on his(companies own site) site and a different offer on other site(like Amazon) I want to store company details for which I did something as below. Next I have created the Direct Offers Last I have created Vendors offer All the models are as below class Company(models.Model): name= models.CharField(max_length=50, null=True) address= models.CharField(max_length=250, null=True) class DirectOffers(models.Model): Smartphone= models.FloatField(max_length=50, null=True) class VendorsOffers(models.Model): Smartphone= models.FloatField(max_length=50, null=True) category = models.CharField(max_length=250, null=True) owner = models.ForeigKeyField("Company",on_delete=models.CASCADE) But the above doesn't seems right So any help or guidance will be a great help. -
Django websocket and webrtc
I have made a Video Confrencing Application using django websocket and WebRTC and hosted on heroku.I am using channel_layer conneted with radis lab.And when i try to connect with two seprate window operating system and they get connected but when i tried the same with mac and windows my websockt tries to connect but failed. js console.log("working"); function createMenuItem(name) { let li = document.createElement('li'); li.textContent = name; return li; } const menu = document.querySelector('#menu'); window.onbeforeunload = function() { return "Are you sure?"; }; var labelUsername=document.querySelector('#label-username'); var usernameInput=document.querySelector('#username'); var btnJoin=document.querySelector('#btn-join'); var count; var username; var mapPeers={}; var webSocket; function webSocketOnMessage(event){ var parsedData= JSON.parse(event.data); var peerUsername = parsedData['peer']; var action = parsedData['action']; if(username==peerUsername){ return; } var receiver_channel_name = parsedData['message']['receiver_channel_name'] if(action == 'new-peer'){ createOfferer(peerUsername,receiver_channel_name); return; } if(action == 'new-offer'){ var offer=parsedData['message']['sdp']; createAnswerer(offer,peerUsername , receiver_channel_name); return; } if(action=="new-answer"){ var answer = parsedData['message']['sdp']; var peer = mapPeers[peerUsername][0]; peer.setRemoteDescription(answer); return; } console.log('message',message); } btnJoin.addEventListener('click',() =>{ username=usernameInput.value; console.log('username :' ,username); if(username=="") { return; } usernameInput.value=""; usernameInput.disabled=true; usernameInput.style.visibility= 'hidden'; btnJoin.disabled=true; btnJoin.style.visibility='hidden'; var labelUsername = document.querySelector('#label-username'); labelUsername.innerHTML=username; var loc =window.location; var wsStart='ws://'; if(loc.protocol=='https:'){ wsStart= 'wss://'; } var endPoint = wsStart +loc.host + loc.pathname; console.log('endPoint:',endPoint); webSocket=new WebSocket(endPoint); webSocket.addEventListener('open',(e)=> { console.log("open"); sendSignal('new-peer',{}); }); webSocket.addEventListener('message',webSocketOnMessage); webSocket.addEventListener('close',(e)=> { console.log("close") }); webSocket.addEventListener('error',(e)=> { console.log("error") … -
PermissionError: [Errno 13] Permission denied: '/var/log/gunicorn.error.log'
I have a Django app and I want to deploy it in docker but I got the error PermissionError: [Errno 13] Permission denied: '/var/log/gunicorn.error.log'. I have no idea anymore where the problem is. could someone help me, please? My dockerfile: # BUILDER # ########### # pull official base image FROM python:3.9.6-slim as builder # set work directory WORKDIR /app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install system dependencies RUN apt-get update \ && apt-get install -y build-essential python3-dev python2.7-dev \ libldap2-dev libsasl2-dev libssl-dev ldap-utils tox \ lcov valgrind \ && apt-get -y install gcc \ && apt install -y netcat # install psycopg2 dependencies RUN apt-get install -y postgresql-server-dev-all musl-dev # lint RUN pip install --upgrade pip COPY . . # install python dependencies COPY requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt # pull official base image FROM python:3.9.6-slim RUN apt-get update && apt install -y netcat # create directory for the app user RUN mkdir -p /home/app # create the app user RUN addgroup --system --disabled-password app && adduser --system --group --disabled-password app # RUN addgroup --system app && adduser --system --group app # RUN adduser --disabled-password --gecos '' app … -
Update in DB column vlaues using django script
I have to update in DB table column name batch_status for which I have written the SQL query here UPDATE farm_management_batch set batch_status = "running" where start_date < now() and batch_status = "to_start" UPDATE farm_management_batch set batch_status = "completed" where batch_status IN ('to_start', 'running') and expected_delivery_date < now() But now I want to write a Django script for this which I have no idea how to do it Here Is the Screenshot -
How to join 2 tables in django ORM
I have 2 Tables. TableA and TableB. id is the primary key in TableB and the foreign key in TableA. My task is to find all the items from TableB where the id should match the item_ids. I am able to get all the items with the below queries. But I'd like to understand how to apply joins on the both tables using select_related to get the same result. item_ids = list(TableA.objects.filter(is_active=True).\ distinct().\ values_list('item_id', flat=True)) items = TableB.objects.filter(Q(id__in=item_ids) & \ Q(display_name__isnull=False) & \ Q(name__isnull=False)).\ values("name", "display_name") Could someone help me with the query? -
Is there a way to mock the firebase_admin credentials.Cerificate class in Django?
In my project, FirebaseAuthentication is used and while running the test cases(pipenv run python manage.py test) I am getting the following error - ValueError: Invalid certificate argument: "None". Certificate argument must be a file path, or a dict containing the parsed file contents. authentication.py from firebase_admin import auth from firebase_admin import credentials cred = credentials.Certificate(os.getenv('FIREBASE_ADMIN_KEY_PATH')) default_app = firebase_admin.initialize_app(cred) tests.py(where I have not imported authentication file) from django.test import TestCase class A(TestCase): .... I am trying to run specific app test case but somehow it is trying to import authentication.py. That is why cred = credentials.Certificate(os.getenv('FIREBASE_ADMIN_KEY_PATH')) is getting executed. I have identified that cred and default_app are declared at global level. And I cannot move it to other function or classes for the same file. I have noticed that cred = credentials.Certificate(os.getenv('FIREBASE_ADMIN_KEY_PATH')) returns the object and not specific data and also calls the Firebase API for authentication. How can I mock this two line at a global level? -
How to do multiple or chained filter functionality dynamically in Django?
context_processors.py def menu_categories(request): subcategories= SubCategory.objects.all() return {'subcategories': subcategories} template {% for subcategory in subcategories%} <li><a href="{{ subcategory.get_url }}">{{ subcategory.title|title}}</a></li> {% endfor %} views.py def products_list(request, subcategory_slug=None, brand_slug=None): if subcategory_slug != None: ----------some filter elif brand_slug != None: ----------some filter else: products = Product.objects.all() context = {'products' : paged_product} return render(request, 'product/products_list.html',context) models.py class Product(DateTimeModel): maincategory = models.ForeignKey(MainCategory, null=True, on_delete=models.CASCADE) productcategory = models.ForeignKey(ProductCategory, null=True,on_delete=models.CASCADE) subcategory_slug = models.SlugField(max_length=300, unique=False, null=True,blank=True) product_slug = models.SlugField(max_length=300, unique=False, null=True, blank=True) ------- ------- def get_url(self): return reverse('product:product_details', args=[self.subcategory_slug, self.product_slug]) I am getting this. I need like this multiple select checkbox filter. It should be done dynamically after the product was added by the vendor. Now, I am done with the single filter results. But, I need to achieve multiple chained filters. Don't know how to do it. Please needed help. -
django jwt "detail": "Authentication credentials were not provided."
I am trying to implement jwt token authentication in my Django Rest Framework application. I am able to receive a token from the django server as you can see POSTMAN request but when I try to get user profile, I got this error. Does anyone have idea?? { "detail": "Authentication credentials were not provided." } I could get access token as you can see. This is SIMPLE_JWT setting in settings.py SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(hours=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=3), 'AUTH_HEADER_TYPES': ('JWT', ), 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken', ) } This is app/urls.py urlpatterns = [ path("admin/", admin.site.urls), path("api/", include("user.api.urls")), path('api/auth/', include('djoser.urls')), path('api/auth/', include('djoser.urls.jwt')), ] This is app/user/urls.py router = DefaultRouter() router.register("api/auth/users/", TraineeRegisterApiView) urlpatterns = [ path('profile/', TraineeProfileApiView.as_view({'get': 'retrieve'})) ] -
Including custom Python module with heroku app?
I've included my python module in my app as follows -myapp -mymodule -__init__.py -setup.py -migrations -template -etc... and to the requirements.txt file. During build, the module is installed along with everything else in requirements, which I believe puts mymodule in brython_stdlib.js, because I am also using brython. The logs confirm the module is installed, but not where. Successfully built mymodule However, when I go to import the module, I get an error. According the the logs I can see that the client is making ajax calls looking for the file. Not Found: /mymodule.py Not Found: /mymodule/__init__.py Not Found: /static/django_brython/js/Lib/site-packages/mymodule.py ... and so on. (I've edited out a lot of lines here, but you get the idea!) So what I think is happening is that the client is not finding the module, and is asking for it from the server. But I can put a mymodule.py in my app and it still does not find it. Of course I would rather not serve ajax calls for this since it should already be installed along with everything else in the requirements file. Please help! I feel really close to getting this to work, but also now it's been feeling that way for … -
Displaying Data in Django using HighCharts
I have text data in a example.txt file in the following format [[Date.UTC(1970, 10, 25), 0], [Date.UTC(1970, 11, 6), 0.25], [Date.UTC(1970, 11, 20), 1.41], [Date.UTC(1970, 11, 25), 1.64], [Date.UTC(1971, 0, 4), 1.6]] Which I am reading in django view.py file as follows filepath = os.getcwd() f = open(filepath+"/main/static/main/data/example.txt", "r") dataset = f.read() def home(request): context = {'dataset': dataset} return render(request, 'main/home.html', context) Loading it in the template as follows <script src="https://code.highcharts.com/highcharts.js"></script> <div id='dataset' data-dataset={{ dataset }} style="width:100%; height:500px;"></div> <script type="text/javascript" src="{% static 'main/js/main.js' %}" ></script> And javascript main.js file with highchart code as follows const app_control = (function() { var sdata; var init_charts; /* VARIABLES INITIALIZATIONS */ /* DEFINE THE FUNCTIONS */ /* Initialize Functions */ init_charts = function(sdata){ const chart = Highcharts.chart('container', { chart: { type: 'spline' }, title: { text: 'Example Data from ' }, xAxis: { type: "datetime", title: { text: 'Date' } }, yAxis: { title: { text: 'Data in Y Axis' } }, colors: ['#06C'], series: [{ name:'Visualized Data', data: sdata }] }) } /* PUBLIC INTERFACE */ public_interface = {}; /* RUN THE FUNCTIONS */ $(function(){ sdata = $('#TimeSeries').data('dataset'); init_charts(sdata); }); return public_interface; }()); The question is, why is the data not visualizing? If … -
last_updated date and time keeps updating everytime the user logs into the system but doesn't update any of their details in Django
In my model for user profile, the profile_last_updated = models.DateTimeField(auto_now=True) keeps updating every time the relevant profile owner logs in but doesn't update any of their details. Is there a way to fix this? I found this on SO django last updated keeps updating when there is no new information but it's a bit confusing. Appreciate any help - thanks! views.py def user_profile_detail_view(request,pk): try: myprofile = get_object_or_404(User, id=pk) except ObjectDoesNotExist: return redirect('handler404') -
Problem Generating Azure ADLS Gen2 SAS Token for Container with Python?
From azure.storage.blob I'm using the function generate_container_sas. I'm trying to generate a SAS token for a container in an ADLS Gen2 storage account in Azure. I can go into azure portal and generate a working SAS token using an account key with no issues. The token works just fine. However, when I do what I think is the same thing in python I get a token back but when I load it into storage explorer it says "Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.". I have validated all the inputs appear to be correct. The token that is generated looks like: https://<STORAGE_ACCOUNT>.blob.core.windows.net/<CONTAINER_NAME>?se=2022-02-19T05%3A41%3A26Z&sp=rwdlac&sv=2020-10-02&sr=c&sig=jCd8AAatl5o9QsbMHtlca6oNnnRdKqtcOnWN3sZa1c8%3D sas_token = generate_container_sas( account_name=account_name, container_name=container_name, account_key=account_key, permission=AccountSasPermissions(read=True, list=True, write=True, delete=True, create=True, add=True), expiry=datetime.utcnow() + timedelta(hours=expiry_hours) ) -
Django messages multiple extra tags
I was trying to pass multiple extra tags in the messages.add_message() as a list. It seemed to work fine while using render, but when I'm trying to use redirect, it passes the extra_tags as a string and I can't get my objects by indexing as it considers the whole list as a string. Is there a way to solve this or pass multiple extra tags? Here is the code- def handleSignup(request): if request.method == 'POST': username = request.POST['signup_username'] name = request.POST['name'] password = request.POST['signup_password'] email = request.POST['email'] if User.objects.filter(username=username).exists(): messages.add_message(request, messages.INFO, 'Please try another username.', extra_tags=['danger', 'Username already taken!']) elif User.objects.filter(email=email).exists(): messages.add_message(request, messages.INFO, 'An account with the email already exists.', extra_tags=['danger', 'Email already in use!']) else: user = User.objects.create_user( username=username, email=email, password=password) user.name = name user.save() messages.add_message(request, messages.INFO, 'Account created.', extra_tags='success') else: return HttpResponse('404 - Not Found') return redirect('/') -
no module name 'django'(already installed django)
I get this error when I run "python3 manage.py runserver" from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' but I already installed and activated django in the virtual environment... I really don't know how to fix it because it worked well before -
Illegal instruction: 4 While running "python manage.py runserver"
Getting the error Illegal instruction and Python stopin macbook pro (os 12.2)