Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
create custom user permissions manually django
i'm trying to create custom permissions , for every user(admin) we have several permissions like (delete,creaet,post,update,view a specific part of the app) , every users have multiple permissions class UserPermission(models.Model): type_of_permission = models.CharField(max_length=30,unique=True) active = models.BooleanField(default=True) def __str__(self): return self.type_of_permission class Meta: db_table = 'user_permission' class UserAccount(AbstractBaseUser): username = models.CharField(max_length=80,unique=True) active = models.BooleanField(default=True) permis = models.ManyToManyField(UserPermission) class Post(models.Model): admin = models.ForeignKey(UserAccount,on_delete=models.CASCADE) title= models.CharField(max_length=80) for example we have type_of_permission = create new post , active = True type_of_permission = delete posts , active = False and so on ,and a user wants to delete a post , i want to filter users by if request.user has delete posts active = False then dont allow that user to delete the object def delete_posts(request,id=id): obj = get_object_or_404(Post,id=id) #how to filter if the requested user have permission to delete post obj.delete() #if not have permission then messages.error(request,'you dont have permission to delete') is it possible to define permissions manually please ? -
Django filter a related model only if a foreign key is not saved as an attribute
I have the following models: class Route(Model): first_stop = models.ForeignKey( Stop, help_text="The departure point", ) last_stop = models.ForeignKey( Stop, help_text="The destination point", ) class Stop(Model): location = models.CharField(max_length=100) route = models.ForeignKey( Route, related_name="stops", related_query_name="stop", help_text="the route that this stop belongs to", ) a route has at least two stops and references to the first and last stops are kept as attributes. I'm trying to filter routes that pass through a specific location but not just on the first or last stop. If the location is only present on its first or last stop then that route should be excluded. If the location is present on an intermediate stop(not first_stop or last_stop) then that route should be included regardless of whether that location is also present on its first or last stop or not. if a route has only two stops then it should be excluded. I made a solution but it's very verbose and ugly and probably inefficient: routes_to_exclude = [] for route in result: # result is a queryset matched_stops = False for stop in route.stops.exclude( pk__in=(route.first_stop_id, route.last_stop_id) ): # to make sure the desired location isn't only on the first or last stop if str(stop.location) == desired_location: matched_stops … -
PyNamecheap update the contact info
recently I'm using PyNamecheap to register domains as it's registering, but I want to configure my domain contacts information for each Registrant, Administrative, Technical and Billing user. but it doesn't provide the option as looked into their code they are just looping through users contact_types = ['Registrant', 'Tech', 'Admin', 'AuxBilling'] and creating with the same details for all account types. and also there isn't any update userinfo method or anything. is there any way to update or customize them while creation and also later to update. -
Pagination not working in DRF even while extending the class from generics
Pagination does not seem to work for me. I am even extending my class from generics, but still it doesn't seem to work. Here is the code for my class class RequestInvite(ListCreateAPIView): authentication_classes = () permission_classes = () serializer_class = RequestInviteSerializer http_method_names = ['post', 'get'] queryset = User.objects.all() And here is the code snippet for my settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 20 } Haven't used any custom pagination class Even defined a default pagination class Still the pagination just does not seem to work. -
How do i render my list of complaints into cards to be able to view them?
I have built a complaint management system, where the system can accept complaints from the users, view and edit them. The user right now is able to submit the complaints and these get stored in the admin panel. For the view complaints page, I have these cards through which they can view the complaints. How do I do that so that only a certain number of cards are seen on the screen. For eg: If there are two complaints, then the user sees two cards and so on. Also how di I display the information in these cards? I'm guessing it'll be through a list and a for loop and stuff but I don't know how. What should I write in the views.py and the forms.py? models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return … -
How To Render An HTML With Css + JavaScript File In Django
Hay, I Have An HTML with Css + JavaScript Page When I Try Rendring This Page In Django Like This: def about(request): return render(request, 'about/index.html') but I Only Get The Html Content Without The Css And JavaScript. I Thought This Might Be Because Of The Statics.. So I Run: python manage.py collectstatic But I Get This: 0 static files copied to 'C:\Users\Ammar\Desktop\Python Learning\vidly\static', 128 unmodified. What Should I Do, I Wish Someone Can Help. -
Extending Django admin delete confirmation page
I am wondering if it is possible to extend Django Admin's delete confirmation page for specific app and model. I want the functionality that enable user to delete all records like that of django admin interface. it is possible to extends delete confirmation.html in my app -
AnonymousUser' object has no attribute '_meta when login by email
I had correct working form to register and login user using username. I add field email to above forms and change to login by email field. Now registered working but login is not. In view sign_in authentication have None value. I have a error 'AnonymousUser' object has no attribute '_meta'. views def sign_up(request): context ={} who ={"teacher": Teacher, "student": Student} form = UserSignUpForm(request.POST or None) context['form'] = form if request.method == "POST": if form.is_valid() and request.POST.get("who"): user = form.save(commit=False) user.set_password(form.cleaned_data['password']) user.save() person = who[request.POST.get("who")] person(user=user).save() messages.success(request, f'{user.email} registered succesfull') return render(request, 'registration/sign_up.html', context) return render(request, 'registration/sign_up.html', context) def sign_in(request): context = {} form = UserLoginForm(request.POST or None) context['form'] = form if form.is_valid(): print('test1') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(email=email, password=password) print(f'email: {email}') print(f'user: {user}') login(request, user) return redirect('/') else: print('test3') attempt = request.session.get('attempt') or 0 request.session['attempt'] = attempt + 1 return render(request, 'registration/sign_in.html', context) return render(request, 'registration/sign_in.html', context) forms class UserSignUpForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UserSignUpForm, self).__init__(*args, **kwargs) self.fields['email'].required = True self.fields['first_name'].required = True self.fields['last_name'].required = True who = forms.ChoiceField( choices=[('student', 'Student'), ('teacher', 'Teacher')], label="", required=True, widget=forms.RadioSelect( attrs={'style':'max-width: 20em; ', 'autocomplete':'off', }) ) password = forms.CharField( label="Password", validators=[MinLengthValidator(8, message="Minimum 8 characters")], widget=forms.PasswordInput(attrs={'autocomplete':'off'})) confirm_password = forms.CharField( label="Confirm password", … -
Is Django automatically apply idexing to pk for fast lookups?
I go through some of the blog post and found i can improve my lookup speed using index, and also in some discussion i found that database usually apply auto indexing to the id or pk of the table without running any manual command. I am currently on two projects which has two different dbs Postgres and MySQL any other suggestion for improving the lookup speed for both the dbs will appreciated. -
why we use * args and **kwargs in super.save()
**As i know, *args is a tuppple and **kwargs is a dictionary and the super.save() is used to override the built-in save method and to ensure that the save() is called but i can't understand why we use in here as parameters ** def save(self,*args,**kwargs): super.save(*args,**kwargs) -
I have configured my uwsgi.ini file and its working fine with nohup. How can auto start uwsgi on boot?
Here is my uesgi.conf code description "uWSGI" start on runlevel [2345] stop on runlevel [06] respawn env UWSGI=/usr/local/bin/uwsgi env LOGTO=/var/log/uwsgi.log exec $UWSGI --master --emperor /home/ubuntu/socialtalks/config --die-on-term --uid socialtalks --gid www-data --logto $LOGTO Here is the ini file configuration. uwsgi.ini [uwsgi] # variables #projectname = thesocialtalks #base = /home/ubuntu/thesocialtalks # configuration #master = true env = /home/ubuntu/socialtalks #pythonpath = %(base) #chdir = %(base) env = DJANGO_SETTINGS_MODULE=%(projectname).settings.production #module = thesocialtalks.wsgi:application #socket = /tmp/%(projectname).sock # mysite_uwsgi.ini file [uwsgi] projectname = socialtalks pcre = true base = /home/ubuntu/socialtalks # Django-related settings # the base directory (full path) #chdir = /home/ubuntu/socialtalks chdir = %(base) # Django's wsgi file #module = socialtalks.wsgi module = %(projectname).wsgi # the virtualenv (full path) #home = /home/admin5/test/thesocialtalks_final/thesocialtalks plugin = python37 # process-related settings # master master = true enable-threads = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe #socket = /home/ubuntu/socialtalks/mysite.sock socket = /tmp/%(projectname).sock # ... with appropriate permissions - may be needed chmod-socket = 666 uid = www-data gid = www-data # clear environment on exit vacuum = true I am ruuning the script using the command nohup uwsgi --ini config/uwsgi.ini &. I want to automate my … -
How to handling timezones in django DRF without repeating myself too much?
Intro: My project TIME_ZONE is equal to 'UTC' while I have users from too many time zones. So, when I user make POST or PUT with date or time or dateTime fields I convert these fields to UTC before serializer.save(). Then, when a user make a GET request I convert the same fields back to the timezone of the user which is request.user.timezone # simplified functions def localize(usertimzone, date, type): date = parser.parse(date) current_user_tz = pytz.timezone(usertimzone) date = paris_tz.localize(date) date = date.astimezone(pytz.utc) #... this is not all the function there are more condition but don't care about the rest return date def normalize(usertimzone, date, type): current_user_tz = pytz.timezone(usertimzone) date = current_user_tz.localize(date) return date #usages example def post(self, request, *args, **kwargs): alert_date = request.data.get('alert_date') if alert_date: request.data['alert_date'] = localize(request.user.timezone, alert_date, 'datetime') Problem: I used these function in too many views and every time I create a new view I use it again. Goal: I need to find a way to do that in one function that generalize this conversion for all dateField, timeField and datetimeField fields. I tried: to make a class view and use these functions inside it then override that class for each new app. But, each model have … -
how to solve SMTPSenderRefused Error in Django
In setting.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'xyz@gmail.com' EMAIL_PASSWORD = '****' EMAIL_USE_TLS = True In views.py admin_info = User.objects.get(is_superuser = True) admin_email = admin_info.email ` send_mail( 'New car inquiry on your website', 'you have a new inwuiry for the car' + car_title + 'Login to your admin panel for more details', 'xyz@gmail.com', [admin_email], fail_silently=False, )` I've disabled two-factor authentication in my gmail, and I've also turned on less secure app access then also I'm getting this error.SMTPSenderRefused error -
How can I do a redirect from the backend Django
I have an application served with React Js for the frontend and Django for the backend. Upon sending some informations to the server, I would like to make a redirect that would occur on the frontend, is it possible ? If so how ? I tried redirecting but it didn't work The front-end (reactJs) async function PaymentHandler(e) { e.preventDefault(); const data = { command_id: order._id, price: order.TotalPrice }; try { const res = await axios.post("/api/orders/Details/", data); } catch (error) { console.log("THERES AN ERROR : ", error); } } return loading ? ( <Loader /> ) : error ? ( <Message variant="danger">{error}</Message> ) : ( <div> <Button variant="outline-primary" className="mt-3" onClick={PaymentHandler} > PAY NOW </Button> </div> ) Model.py class Stuff(models.Model): paymentDetails = models.JSONField() Model serializer class PaymentSerializer(serializers.ModelSerializer): paymentDetails = serializers.JSONField() class Meta: model = Stuff fields = '__all__' views.py from rest_framework.decorators import api_view from django.shortcuts import redirect from base.models import Stuff from base.serializers import PaymentSerializer import requests import json @api_view(['POST']) def getPaymentDetails(request): data = request.data payment = Stuff.objects.create( paymentDetails = data ) serializer = PaymentSerializer(payment, many=False) last = Stuff.objects.last() details = (last.paymentDetails) print('cmd id value :', details['command_id']) print('price id value :', details['price']) headers = {"Content-Type": "application/json","Authorization": "Bearer eyJ0exxxxxxxxxxxx"} url = "https://apps.somewebsite.com/" payload … -
Converting bytes to file in Django / Python
In my Django app, I have a PDF in bytes: print(myPDF) > b'%PDF-1.3\n1 0 obj\n<<\n/Type /Pages\n/Count 2.... I want to save it in my database: obj.document = myPDF obj.save() However I keep getting an 'bytes' object has no attribute '_committed' error on save. How can I convert my bytes string to a file-like object that can be saved? -
What is the difference between . and __ in Django?
Can someone help me to understand the actual difference between . and __ with proper example. -
I want to create a form form by inputting a form and a form form using ModelChoiceField
Currently, Django is creating a soccer game player information site. I would like to add a search function that combines pull-down and input form. As a search method, select the player name category (models.py: player_style) from the pull-down menu, enter the player name (models.py: player_name), and search for the player name. I used "ModelChoiceField" as the code and entered form.py and views.py, but it stopped due to an error. Since I'm new to Django, I have a lot of questions, so can you tell me what kind of code to write? Since the questioner is Japanese, It will be poor English, but thank you. models.py class Player(models.Model): player_style = models.CharField('player_style', max_length=20) player_name = models.CharField('player_name', max_length=50) def __str__(self): return self.player_name form.py from django import forms from django.forms import ModelChoiceField from .models import Player class MyModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return "%i" % obj.player_style + " %s" % obj.player_name views.py from .forms import MyModelChoiceField def filters(request): form = MyModelChoiceField(queryset=Player.objects.all()) if(request.method == 'POST'): form = form() player = request.POST['form'] data = Player.objects.filter(player_name=player) msg = 'results:'+str(data.count()) else: msg = 'search words...' form = form() data = Player.objects.all() params = { 'title': 'Player results', 'form': form, 'message':msg, 'data':data, } return render(request, 'filters.html', params) filters.html <h3 class="display-4 … -
How can we pass element ID as a variable in an AJAX request?
I am trying to write a template that will create a blog feed, like blogging websites with multiple instances of the same kind. Now, each instance (each blog post) needs its own like button. For implementing this feature, I am using AJAX. I am able to make changes in the database by clicking the 'follow' button but not able to make changes in the template with the success function. Here is the template, {% for question, count, is_follow in zipp %} <div class="border rounded my-2 px-3 py-1" style="box-shadow: 2px 2px 5px #2b6dad;"> <p class="fst-normal"> <small>Tags: </small> {% for tag in question.tags.all %} <small><a href="{% url 'tag' tag.slug %}" style="text-decoration:none; color:black"><i>{{tag.name}} |</i></a></small> {% endfor %} </p> <p><a href="{{question.get_absolute_url}}" style="text-decoration: none; color: black"><h5>{{ question.question }}</h5> <small>Arguments added: {{ count }}</small></a></p> <div class="blank" id="{{question.question_id}}"> {% include 'snippets/follow_question.html' %} </div> <button type="button" class="btn btn-secondary btn-sm mt-1"><i class="fa fa-share-alt" style="padding-right: 3px;"></i>Share</button> </div> {% endfor%} Script <script type='text/javascript'> $(document).ready(function(event){ $(document).on('click', '#follow', function(event){ event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: '{% url 'follow_question' %}', data: {'id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, datatype: 'json', success: function(response){ var id = $(this).closest('.blank').data('id'); $(id).html(response['form']); }, error: function(rs, e){ console.log(rs.responseText); }, }); }); }); </script> As far as I understand, … -
AttributeError: 'Seekerskillset' object has no attribute 'skill_name'
I am trying to implement bulk_create my inserting multiple objects in a relation, not sure whether i am doing it right my view skill_name = request.POST.getlist('skill_name') skill_level = request.POST.getlist('skill_level') print(f'skill name-> {skill_name} skill level ->{skill_level}') seeker_skll = [] # testing destructing for skill_nme, skill_lvl in zip(skill_name, skill_level): skill_set = Skillset.objects.get(skill_name=skill_nme) seeker_skll.append(Seekerskillset( skill_set=skill_set, skill_level=skill_lvl, seeker=user)) seeker_skll = Skillset.objects.bulk_create(seeker_skll) print(seeker_skll) return redirect('/users/dashboard') Model class Seekerskillset(models.Model): skill_set = models.ForeignKey(Skillset, on_delete=models.CASCADE) seeker = models.ForeignKey(SeekerProfile, on_delete=models.CASCADE) skill_level = models.CharField(max_length=25) class Meta: verbose_name = 'Seeker skill set' error i am getting AttributeError: 'Seekerskillset' object has no attribute 'skill_name' -
Is Foreign Key Constraint mandatory? Why not just keep the key and not the constraint?
Is Foreign Key Constraint mandatory? Why not just keep the key and not the constraint? For Eg: class SalesOrderSummary(models.Model): id = models.BigAutoField(primary_key=True) uuid = models.UUIDField(default=uuid.uuid4, editable=False) # Order Status values could : CONFIRMED, DISPATCHED, DELIVERED order_status = models.CharField(max_length=255, blank=False, default='') class SalesOrderItem(models.Model): """ Line item details of the particular sales order, mostly they are grouped by seller, for easy processing """ id = models.BigAutoField(primary_key=True) uuid = models.UUIDField(default=uuid.uuid4, editable=False) # Here I don't keep the ForeignKey Constraint, but I understand the constraint # and manage it myself, like whenever Order is deleted, these items are also # getting deleted sales_order_id = models.BigIntegerField() seller_sku = models.CharField(max_length=255, blank=False, default='') product_title = models.CharField( max_length=255, blank=False, default='') quantity = models.BigIntegerField() unit_price = models.DecimalField( max_digits=10, decimal_places=2, default='0.00') I totally agree that these FK Constraints, are here to make our life easy by making it to do our jobs. like automatically deleted when the associated main entity gets deleted. If I can manage that myself, then where is the problem. So let me know if I would encounter any dead end or something or some feature that's not at all possible. -
Data changing when multiple users are logged in with Discord OAuth2
I'm making a Django app with Discord OAuth2 so users can log in. When 2 users log in, the data appears on both screens. So if you log in, it'll show your data but if you reload the page, it'll show another user's data. Does anyone know why this happens? I know it's a lot of code but any help would be immensely appreciated. Views.py client_id = "client_id_here" @login_required(login_url="app/oauth2/login") def main(request: HttpRequest): username = user['username'] guild = [guild for guild in guilds if int(guild["permissions"]) & 0x00000020 == 32] connection = connection db = connection.cursor() query = db.execute("select server_count from info") servers = db.fetchone() servers = servers[0] query = db.execute("select user_count from info") users = db.fetchone() print(f"users: {users}") users = users[0] db.close() connection.close() return render(request, "home/index.html", { "username": username , "guilds": guilds, "guilds": guild, "servers": servers, "users": users }) def discord_login(request: HttpRequest): return redirect('https://discord.com/api/oauth2/authorize?client_id=707641033210593351&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fapp%2Foauth2%2Flogin%2Fredirect&response_type=code&scope=identify%20guilds') def discord_login_redirect(request, *args, **kwargs): code = request.GET.get("code") exchange_user = exchange_code(code) discord_user_auth = DiscordAuthenticationBackend.authenticate(request=request, user=exchange_user) discord_user_auth = list(discord_user_auth).pop() login(request, discord_user_auth) return redirect("/app") def exchange_code(code: str): data = { "client_id": client_id, "client_secret": "secret", "grant_type": "authorization_code", "code": code, "redirect_uri": "http://localhost:8000/app/oauth2/login/redirect", "scope": "identify guilds" } headers = { 'Content-Type': 'application/x-www-form-urlencoded' } validate_token = requests.post("https://discord.com/api/oauth2/token", data=data, headers=headers) credentials = validate_token.json() access_token = … -
Search and display one row from Django Rest Api
after followed many tutorials about how to integrate Django rest in React I succeeded to fetch data from my API like this, but when I try to fetch just one row by the ID it becomes difficult to do, so in my project, I can add employees and display them all, but the problem is when I try to search for a specific employee by his ID, this is the code which can display all the employees import React from "react"; class List extends React.Component { constructor() { super(); this.state = { data: [], Matricule: "", }; this.changeHandler = this.changeHandler.bind(this); } changeHandler(event) { this.setState({ [event.target.name]: event.target.value, }); // console.log(event.target.name); // console.log(this.state.Matricule); } fetchData() { fetch("http://127.0.0.1:8000/employee/") .then((response) => response.json()) .then((data) => { this.setState({ data: data, }); console.log(data); }); } componentDidMount() { this.fetchData(); } render() { const emp = this.state.data; const rows = ( <tr key={emp.id}> <td>{emp.Matricule}</td> <td>{emp.Nom}</td> <td>{emp.Prenom}</td> <td>{emp.Terminal}</td> <td>{emp.Fonction}</td> <td>{emp.Statut}</td> </tr> ); console.log(this.state.Matricule); return ( <div> <h1>Liste des employes</h1> <input value={this.state.Matricule} name="Matricule" onChange={this.changeHandler} type="number" className="form-control" /> <table className="table table-bordered"> <thead> <tr> <th> Matricule</th> <th>Nom</th> <th>Prenom</th> <th>Terminal</th> <th>Fonction</th> <th>Statut</th> </tr> </thead> <tbody>{rows}</tbody> <button className="btn btn-danger px-1 ">chercher</button> </table> </div> ); } } export default List; -
Saving user registration data from DRF to Postgresql database?
i am building an app with an user registration with the help of django rest framework, i want to store my user's data in my postgresql database, i can see my model on my pgAdmin but after made a post request to register my user i cant retrieve my data on the database. So how can i save those data on the database ? models.py from django.db import models # Create your models here. class User(models.Model): username = models.TextField() email = models.TextField() password = models.TextField() serializers.py from rest_framework import generics, permissions from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) class Meta: model = User fields = ( 'username', 'email', 'password') def create(self, validated_data): user = super(UserSerializer, self).create(validated_data) user.set_password(validated_data['password']) user.save() return user views.py from rest_framework import generics from rest_framework.permissions import AllowAny from .models import User from .serializers import UserSerializer class UserCreateAPIView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (AllowAny,) -
Creating Django model fields dynamically from method variables during migration
One of my app's models has a few pre-defined fields, let's say: class Data(models.Model) user = models.CharField(max_length=50) date = models.DateTimeField() It also has a few fields that are based on variables passed in to the methods of a class which I would like to name "method_variable". Below is a sample class from which I would like to add meth0_var0 and meth0_var1 as CharFields in the Data model. class A: def meth0(self, var0, var1) ... I would like to dynamically add those variables to my model whenever I migrate the database (basically just saving myself the labor of writing out all the fields as there are many). So far I have tried adding this to my models.py after defining the model: methods = {k: v for k, v in dict(A.__dict__).items() if '__' not in k} # get rid of __init__ and such for key in methods: args = [arg for arg in getfullargspec(methods[key]).args if arg != 'self'] # get rid of self / methods that don't have any input variables [setattr(Data, f'var_{key}_{arg}', models.CharField(max_length=50, default='Unrecorded')) for arg in args] # use what's left to create attributes in the class for migration When I try to run makemigrations it finds no new fields … -
How to implement auth0 loging, register, authorization, permission in Django?
I am looking for learning auth0 with Django. but not getting any resources for register, login, authorization, and permission. Can anyone help me with that?