Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Status (Draft - Published) & Time (Published, Created, Updated) Issues
This is my model. Appears on admin side but not working. models.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) published = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=9, choices=STATUS_CHOICES, default='draft') -
Set maximum value of integer field in template from context Django
I have a regular form with the basic template: <form method="post" action=""> {% csrf_token %} {{ form }} <input type="submit" value="submit"> </form> The form consists of three integer fields defined in forms.py class InitForm(forms.Form): row_1 = forms.IntegerField(initial=1, min_value=1) row_2 = forms.IntegerField(initial=1, min_value=1) row_3 = forms.IntegerField(initial=1, min_value=1) The maximum value is set at runtime using input from the user. I have added it to the context by using get_context_data()... in the form view class, but how do I set the maximum input value for the three integer fields in the template? I can already output the maximum value in the template by {{ maximum_value }} I am just having trouble adding it to the form fields. For reference I need the maximum value on all the fields -
Django Thinking User Is Logged In On One Page Only But on The Rest They Are Not
So I created a user profile by following this tutorial https://www.oodlestechnologies.com/blogs/How-to-Edit-User-Profile-Both-Django-User-and-Custom-User-Fields/ but every time I go the profile page when not logged in it shows that I am logged in I don't know if django thinks im the user that the profile im viewing. I tested it by adding this into the base.html <p>{% if user.is_authenticated %} You are logged in {% endif %}</p> It doesn't show it on any pages because im not logged in unless I go to view someones profile then it says im logged in which I am not models.py class UserProfileManager(models.Manager): pass class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='avatars', blank=True) location = models.CharField(max_length=100, default='', blank=True) date_of_birth = models.DateField(default='00/00/0000', null=True, blank=True) website = models.URLField(default='', blank=True) bio = models.TextField(default='', blank=True) def __str__(self): return self.user.username def age(self): dob = self.date_of_birth tod = datetime.date.today() my_age = (tod.year - dob.year) - int((tod.month, tod.day) < (dob.month, dob.day)) return my_age def createProfile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.created(user=kwargs['instance']) post_save.connect(createProfile, sender=User) views.py def public_profile_view(request, username): user = User.objects.get(username=username) userprofile = UserProfile.objects.all() # date_joined = request.user.date_joined # last_login = request.user.last_login context = { 'user': user, 'userprofile': userprofile, # 'date_joined': date_joined, # 'last_login': last_login, } return render(request, "/account/profile/public_profile.html", context) def profile_edit_view(request): userprofile = … -
How do I fetch all the items in a list from an external API in Django?
So this is my api - https://api.myjson.com/bins/vvjiu Here is a portion of my view.py def postsign(request): product_list = Product.objects.all() product_data = [] for product in product_list: r = requests.get('https://api.myjson.com/bins/vvjiu').json() products = { 'name': r['products'][0]['name'], 'image': r['products'][0]['image'], 'price': r['products'][0]['price'], 'description': r['products'][0]['description'] } product_data.append(products) print(product_data) context = {'products':products} return render(request,"Welcome.html",context) And here's my product view in Welcome.html div class="container carousel-inner no-padding"> <div class="col-xs-3 col-sm-3 col-md-3"> {% for products in product_data %} <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{ products.image }}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ products.name }}</h5> <p class="price">{{ products.price }}</p> <p class="card-text">{{ products.description }}</p> <a href="#" class="btn btn-primary">Add to cart</a> </div> </div> {% endfor %} </div> </div> This returns just the first item from the API, that is, the Acoustic Guitar. But I want to get the rest of the items as well. What do i need to fix? -
I am not able to go into my virtual environment
I am new to programming. I recently started learning Django by following the tutorials on Mozilla. I created a python virtual environment by following the steps in the tutorial. However, I am not able to activate the virtual environment that I have created. As . a result, I am not able to progress on the tutorials. I have spent hours trying trying to find a solution on Google, but nothing seems to work. I have attached a picture of the terminal window where you can see the commands I am entering and the results. hemantasundaray@Deepaks-MacBook-Pro ~ % source createdenv/bin/activate source: no such file or directory: createdenv/bin/activate hemantasundaray@Deepaks-MacBook-Pro ~ % ls virtualenv ls: virtualenv: No such file or directory hemantasundaray@Deepaks-MacBook-Pro ~ % workon zsh: command not found: workon hemantasundaray@Deepaks-MacBook-Pro ~ % What am I doing wrong? Kindly help.enter image description here -
Setup Django with webpack-dev-server
setting up webpack-dev-server with Django has not been working. I have looked at many stackoverflow questions and read tuts but I can't seem to find what I am doing wrong. Here are the errors I get: webpack fails compiling with a ton of ERROR in ./node_modules/[package_name]/index.js Module not found: Error: Can't resolve '[tls or fs or net]' in '/Users/user_name/project_folder/sub_folder/node_modules/[package_name]' Even with webpack failing the browser load http://localhost:8080 with Cannot GET / error on it I am using webpack-dev-server : "^3.9.0" Here is my webpack.config.js var path = require("path"); var BundleTracker = require('webpack-bundle-tracker'); var CleanWebpackPlugin = require('clean-webpack-plugin'); var MiniCssExtractPlugin = require('mini-css-extract-plugin'); var TerserPlugin = require('terser-webpack-plugin'); var webpack = require('webpack') var rules = mode => { return [ { test: /\.(ttf|eot|svg|woff|woff2|svg)?(\?[a-z0-9#=&.]+)?$/, loader: 'file-loader', }, { test: /\.(js|jsx|mjs)$/, exclude: /node_modules/, loader: 'babel-loader', options: { presets: [ ['@babel/preset-env', { corejs: 3, useBuiltIns: 'usage' }], ['@babel/preset-react'], ], plugins: [ ["babel-plugin-styled-components"], ["@babel/plugin-proposal-decorators", { legacy: true }], ["@babel/plugin-proposal-class-properties", { "loose": true }], "react-hot-loader/babel" ], cacheDirectory: true } }, // to transform JSX into JS { test: /\.(sa|sc|c)ss$/, use: [{ loader: MiniCssExtractPlugin.loader, options: { hmr: mode === 'development' ? true : false, }, }, { loader: 'css-loader', options: { importLoaders: 1 } }, 'postcss-loader', 'resolve-url-loader', 'sass-loader', ], } … -
Django set user's language based on IP then remember it in session with custom middleware
I want to play a little bit with language settings and have some problems through [TODO] set users location based on theirs IP - DONE (code below) some customers may want to change language. Example scenario: user lives in germany (and has German IP), middleware sets language to DE based on users IP but then user switch language to EN and want to hold that state in session. For now every time I run this code, it gives me language based on IP. Do you have any ideas where the bug is? . from typing import Callable from django.conf import settings from django.contrib.gis.geoip2 import GeoIP2 from django.http import HttpRequest, HttpResponse from django.utils import translation from geoip2.errors import AddressNotFoundError from utils.middleware import logger DE_COUNTRIES = ['DE', 'AT', 'CH', 'LI', 'LU'] def get_request_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip class UserIpAddrMiddleware: def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None: self.get_response = get_response def __call__(self, request: HttpRequest) -> HttpResponse: if hasattr(request, 'session'): current_language = request.session.get(translation.LANGUAGE_SESSION_KEY, None) if not current_language: request_ip = get_request_ip(request) g = GeoIP2() try: request_country_code = g.country(request_ip)['country_code'] if request_country_code == 'PL': request.session[translation.LANGUAGE_SESSION_KEY] = 'pl' request.session[settings.CURRENCY_SESSION_KEY] = 'PLN' elif request_country_code in DE_COUNTRIES: request.session[translation.LANGUAGE_SESSION_KEY] = 'de' … -
Querying datetime object in django doesn't work
I'm facing the issue of wrong query result due to timezone issue. I've read several answers, but most of suggest USE_TZ = False. But we can't do that because of several dependencies on time zone. blog = Post.objects.filter(date_posted__year=2019, date_posted__month=11) blog[0] Post: asfd random new india safasfd adf hey blog[0].date_posted datetime.datetime(2019, 11, 26, 20, 33, 58, tzinfo=) blog[0].date_posted.day 26 When I query on day 26 it throws error: Post.objects.get(date_posted__year=2019, date_posted__month=11, date_posted__day=26, slug=blog[0].slug) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/insol/webD/trydjango/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/insol/webD/trydjango/lib/python3.7/site-packages/django/db/models/query.py", line 408, in get self.model._meta.object_name Blog.models.Post.DoesNotExist: Post matching query does not exist. But it works on day 27. Post.objects.get(date_posted__year=2019, date_posted__month=11, date_posted__day=27, slug=blog[0].slug) Output: <Post: asfd random new india safasfd adf hey> Is there any I can solve this issue? -
Celery-Django, Start and stop reminder emails for survey
I'm trying to implement a recurring daily reminder email task into my program that begins at a specific date/time and is stopped only when the customer completes the required action. Is this something that is possible with Celery and Django? I've already found a way to send a one time task email via ETA- though am unsure how to set up a recurring event that can then be cancelled. Thanks for your time. -
What is /?next=/ in url django?
i wonder why my url is http://localhost:8000/?next=/randomization/ when I directly type http://localhost:8000/randomization/ in the browser for an unauthorized user? -
Pagedown (markdown editor) in Django not previewing forms
I installed django-pagedown app for my blog web application. But when I edit or add a new blog post, it's not previewing my form. Following are some file content which I would like to share with you. settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', '''-------------thirdPartyApps-----------------''' 'markdown_deux', 'pagedown', 'accounts', # custom apps 'posts', # custom apps forms.py file from django import forms from pagedown.widgets import PagedownWidget from .models import Post class PostForm(forms.ModelForm): content = forms.CharField(widget=PagedownWidget()) publish = forms.DateField(widget=forms.SelectDateWidget) class Meta: model = Post fields = ( "title", "content", "draft", "publish", ) form.html file {% extends "base.html" %} {% load crispy_forms_tags %} {% block head_extra %} {{ form.media }} {% endblock head_extra %} {% block content %} <div class='col-sm-6'> <h1>Preview</h1> <hr/> <div class='content-preview'> <h3 id='preview-title'></h3> <p id='preview-content'></p> </div> </div> <div class='col-sm-6'> <h1>Form</h1> <hr/> <form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %} {{ form|crispy }} <input type='submit' class='btn btn-default' value='Create Post' /> </form> </div> {% endblock content %} Where am I getting wrong? Could someone please help me in it? -
Django Forms in Modal not rendering
i am trying to get my form to render in a Modal, however the modal show up empty. the code below illustarte my work and i appreciate feedback to resolve this problem. Model: class Startup ( models.Model ) : author = models.OneToOneField ( User , on_delete = models.CASCADE ) startup_name = models.CharField ( 'Startup Name' , max_length = 32 , null = False , blank = False ) class Startup_About ( models.Model ) : str_about = models.ForeignKey ( Startup , on_delete = models.CASCADE ) about = models.TextField ( 'About Startup' , max_length = 2000 , null = False , blank = False ) problem = models.TextField ( 'Problem/Opportunity' , max_length = 2000 , null = False , blank = False ) business_model = models.TextField ( 'Business Monitization Model' , max_length = 2000 , null = False ,blank = False ) offer = models.TextField ( 'Offer to Investors' , max_length = 2000 , null = False , blank = False ) View: def create_startupaboutform(request) : stup = Startup.objects.filter(author=request.user) if request.method == 'POST' : form = startupaboutform ( request.POST ) if form.is_valid ( ) : instance = form.save ( commit = False ) instance.str_about = stup instance.save ( ) return redirect ( … -
Django_tables2 How to identify each table when using MultiTableMixin in Django Template
I am trying to render two seperate tables on a different location in a Django template. However, the official documentation only shows how to render the tables in a loop: {% for table in tables %} {% render_table table %} {% endfor %} This works, however, I want to render a table based on a identifier(such as name). The following code does this, but it doesn't make it clear what table is being rendered: {% render_table tables.0%} Something among the lines of: {% render_table tables.newstable %} would be ideal. I've had slight succes by removing the MultiTableMixin class, then rendering the tables using get_context_data(), however, this breaks pagination. def get_context_data(self, **kwargs): context = super(TeamHomeTest, self).get_context_data(**kwargs) team_id = self.kwargs['teamid'] team = Tmteams.objects.get(teamid=team_id) q1 = Tmteamsusers.objects.all().filter(teamid=team_id) category_ids = [] categories = nwscategory.objects.all().filter(teamId=team_id) for cat in categories: category_ids.append(cat.categoryid) q2 = nwseditor.objects.filter(categorie_id__in=category_ids) team_member_list_table = TeamMemberListTable(q1) team_news_list_table = TeamNewsTable(q2) context['table1'] = team_member_list_table context['table2'] = team_news_list_table context['team'] = team self.tables=[context['table1'], context['table2']] return context My current get_tables() method looks like this: def get_tables(self): team_id = self.kwargs['teamid'] q1 = Tmteamsusers.objects.all().filter(teamid=team_id) category_ids = [] categories = nwscategory.objects.all().filter(teamId=team_id) for cat in categories: category_ids.append(cat.categoryid) q2 = nwseditor.objects.filter(categorie_id__in=category_ids) table1 = TeamMemberListTable(q1) table1.name = "test" tables = [ table1, TeamNewsTable(q2) ] return tables -
How to use Django builtin auto form and summernote
I tried to implement summernote functionality on my commentForm page but when I installed django-summernote into my app, the commentForm refused to show up again on the browser. Please, where did I got it wrong? form.py from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget class CommentForm(forms.ModelForm): text = forms.CharField(widget=SummernoteInplaceWidget()) class Meta: model = Comment fields = {'text': SummernoteWidget(), } commentForm.html <form method="post" class="post-form-blog"> {% csrf_token %} {{ form.as_p}} <button type="submit" class="btn btn-success">Post</button> </form> models.py class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comment') author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now()) approved = models.BooleanField(default=False) def approve(self): self.approved = True self.save() def __str__(self): return self.text admin.py from django.contrib import admin from .models import Post, Comment from django_summernote.admin import SummernoteModelAdmin class PostAdmin(SummernoteModelAdmin): summernote_fields = ('text',) # Register your models here. admin.site.register(Post, PostAdmin) admin.site.register(Comment) urls.py from django.conf import settings from django.urls import path, include from . import views from django.conf.urls.static import static urlpatterns = [ path('summernote/', include('django_summernote.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Thank you! -
I want to be Back-end Developer
I want to be Back-end Developer but I don't know even Bootstrap,Javascript,Css.Is it need for back-end development? Now I learn Flask, Django for back-end Development. Thanks for attention. -
Django sending context to multiple views
I'm trying to achieve following tasks in Django: First page: User fills a large Job application form and that data is sent to Second page Second page: User reviews his previously filled data and proceeds to third page Third page: User pays the amount(came from Second page) and once paid, then only all this data is saved to DB. I've done First page work of filling form and then sending that data to Second page. Here's my views.py def applyJob(request,id=None): job = get_object_or_404(AddJob, id=id) if request.method == 'POST': context = { 'jobName': job.jobName, 'jobID' : job.pk, 'cfName' : request.POST.get('candidateFirstName'), 'cmName' : request.POST.get('candidateMiddleName'), 'clName' : request.POST.get('candidateLastName'), ...... return render(request,'reviewAppliedJob.html',context) else: context ={ "jobName": job.jobName, "id": id, } return render(request,'applyJob.html',context) Since I'm sending the context data using return render(request,'reviewAppliedJob.html',context), URL is not changing and so it's not going to my reviewAppliedJob views and so I cannot write code to go to Third page. def reviewAppliedJob(request): return HttpResponse('done....') For that, I can use HttpResponseRedirect('/reviewAppliedJob') instead of render in applyJob() but it will not send my context data. Django allows sending context either using render(), messages framework, url params or session. But since I have large amount of data, I don't know which one … -
Signup page redirecting to same page without printing any error
After POST method signup page always redirects to same page without printing any message or redirecting to homepage or login page but I am tracing it in every steps by printing something to check how it is working. But I can signup a new user using python shell. Terminal is giving me only this: [28/Nov/2019 15:36:26] "GET / HTTP/1.1" 200 2574 [28/Nov/2019 15:36:46] "POST / HTTP/1.1" 200 2574 def signup(request): if request.user.is_authenticated: return render(request,'/',{}) form = UserForm(request.POST or None) if request.method == 'POST': print("step 2") if form.is_valid(): user = form.save(commit= False) username= form.cleaned_data['username'] password= form.cleaned_data['password'] user.set_password(password) user.save() authenticate(username= username, password= password) Profile.objects.create( user= user, full_name=form.cleaned_data['full_name'], codeforces_id= form.cleaned_data['codeforces_id'], Uva_Id = form.cleaned_data['Uva_Id'], points = 0, department= form.cleaned_data['department'] ) if user is not None: if user.is_active: login(request,user) return redirect('/') return render(request, 'signup.html',{'msg':'Invalid'}) else: error = form.errors print("error step") return render(request, 'signup.html',{'msg':error}) else: return render(request,'signup.html',{}) forms.py: class UserForm(forms.ModelForm): password = forms.CharField(widget= forms.PasswordInput) full_name = forms.CharField(required= True) codeforces_id = forms.CharField(required= True) Uva_Id = forms.CharField(required= True) department = forms.CharField(required= True) class Meta: model = User fields=('username','email','password','full_name','codeforces_id','Uva_Id','department') signup.html: <body> <div class="wrapper"> <div class="inner" style="width: 500px;"> {% block content %} <form action="" method="post" style="padding-top: 40px; padding-bottom: 50px"> {% csrf_token %} <h3 style="margin-bottom: 20px">New Account?</h3> <div class="form-group"> <label for="username" … -
Html select POST Django
Hello i'm new to django. I have a model that looks like this. Models.py class CustomUser(AbstractUser): pass first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def __str__(self): return self.username class Campus(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Intervention(models.Model): subject = models.CharField(max_length=200) begin_date = models.DateField(default=datetime.datetime.today) end_date = models.DateField(default=datetime.datetime.today) description = models.TextField(blank=True) speaker = models.ForeignKey(CustomUser, on_delete=models.CASCADE) campus = models.ForeignKey(Campus, on_delete=models.CASCADE) class Meta: verbose_name = 'Intervention' verbose_name_plural = 'Interventions' def __str__(self): return self.subject class Evaluation(models.Model): interventions = models.ForeignKey(Intervention, on_delete=models.CASCADE) student_id = models.CharField(max_length=20) speaker_knowledge_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)]) speaker_teaching_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)]) speaker_answer_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)]) slide_content_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)]) slide_examples_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)]) comment = models.TextField(blank=True) class Meta: verbose_name = 'Evaluation' verbose_name_plural = 'Evaluations' So, basically what i'm trying to do is on home page i want to have a select box where student have to choose his campus then he will be redirected to a new page where he can see only the interventions that belongs to the campus he choosed My home page looks like this: <form method="post" action="/Mark/"/> <select name="campus_id"> <option value="" disabled selected>Choose your Campus</option> {% for camp in campus %} <option value="camp.pk">{{ camp.name }}</option> {% endfor %} </select> <input type="submit" /> </form> I tried several things but none worked … -
Django Channels: issue using sessionStorage to store username with JavaScript, better way to store variable?
I am using Django Channels to build a chat app. It is not backed by a database and I am trying to handle everything via JavaScript. The program works except for a problem with sessionStorage. The error I am getting is that the username always displays as the username in the active browser. For example, if there are two users in a room, User1 and User2, all messages on User1's screen will display as from User1, even those sent from User2. On User2's screen all message show as from User2. Here is the code handling the chat window: // Declare variables var userName; document.getElementById("chatname").innerHTML = roomName; // Set User window.onload = function(){ userName = sessionStorage.getItem("user"); if (userName==null || userName===false) { userName = prompt("Please enter a username:"); }; return userName; } // Create Websocket var chatSocket = new ReconnectingWebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/'); // Send message chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data['message']; var currentDate = new Date(); var currentTime = currentDate.toLocaleTimeString(); document.querySelector('#chat-log').value += (userName + " " + currentTime + ': ' + message + '\n'); document.getElementById("chat-log").scrollTop = document.getElementById("chat-log").scrollHeight; }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; document.querySelector('#chat-message-input').focus(); … -
How to make calls to the centralized MySQL database from my django website?
Lets say I have two systems that will runs a Django server and one system that will be a centralised database that will only contain database application running on this machine. How can I have two machines connect to same database i.r Read/Write from/to database? What software needs to be running on my MySQL database side so it can get the data from the server and return the data from the database in case of read query ? The question is how can two server make connection to a centralized database to read/write from it? What code/technologyn should be running on the database server to send/receive data? If there are to systems that are solely dedicated as a server and one as a database then how can I make a connection from my two server machine to the centralized database. Which technologies can help me in achieving this? What code should be run on the third machine and how the other two server makes connection to this database? -
custom user model with slug field
I have a custom user model, and I want to add a slug field in Django. T problem is I don't know how it should be handled in the user manager. please help me out. Note: I use signals to create the slug field model.py class UserManager(BaseUserManager): def _create_user(self, email, fullname, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) fullname = fullname user = self.model( email=email, fullname=fullname, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, fullname, password, **extra_fields): return self._create_user(email, fullname, password, False, False, **extra_fields) def create_superuser(self, email, fullname, password, **extra_fields): user=self._create_user(email, fullname, password, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(max_length=254, unique=True) fullname = models.CharField(max_length=250) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=255, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['fullname'] objects = UserManager() def __str__(self): return self.email signals.py @receiver(pre_save, sender=settings.AUTH_USER_MODEL) def add_slug_to_user(sender, instance, *args, **kwargs): if instance and not instance.slug: slug = slugify(instance.fullname) random_string = generate_user_string() instance.slug = slug + "-" + random_string the problem is how do I handle the slug field … -
Can i use a picklist to display attending users and absent users in the admin environment of django?
Right now I have 2 lists displayed with the exact same content. One is used for selecting attending users and the other one is used for the users that are absent during the meeting. This doesn't look nice. I would like to have 2 list views next to each other. The first one is the attending list view which has all the users shown. The absent list is empty but i can drag or use a cursor button to swap users from the Attend list to the Absent list. To give you an example of what i mean: Heres an example component in angular primefaces. https://www.primefaces.org/primeng/#/picklist If you select a car brand in the left list and press the upper button then the car brand will be removed from the left list and displayed in the right list. Does django support such a display feature? Thank you -
Reason to use Postman for Django Rest Framework
I'm used to test Django Rest Framework apps with the test tools available directly in Django and DRF. It's possible to setup a dummy client and expose all the REST methods. At the same time, I see many posts talking about Postman for API testing. I fail to see where the advantage would be. Is there any reason for me, a single developer, to use Postman? Or perhaps there is only an advantage for shared projects? -
Django Rest Framework with knox gives 'Token' has no attribute 'DoesNotExist' when trying to access a view
I am using drf with knox, and have reached a stage at which I can login, with basic auth, and receive a token in response. When I then try to make another request with that token, the server gives a 500 with the following error: rest_framework.request.WrappedAttributeError: type object 'Token' has no attribute 'DoesNotExist' With this being the beginning of the traceback: Traceback (most recent call last): File "/home/foo/.virtualenvs/server/lib/python3.8/site-packages/rest_framework/authentication.py", line 194, in authenticate_credentials token = model.objects.select_related('user').get(key=key) AttributeError: type object 'Token' has no attribute 'objects' Obvious troubleshooting: knox is installed knox is migrated Default auth method for DRF is knox.TokenAuthentication drf's authtoken is not in installed apps -
User has no permission in admin screen even if the associated group has all perms - Django 2.2
I have created a new group "finance" in my django website. I would like to assign this group some permissions and users to this group. In order to test, I am assigning myself in this group and removing me from superuser. Even if this group has all the perms, I am getting You don't have permission to view or edit anything. message once on the admin screen. According to django: A user will get all permissions granted to each of their groups. Am I missing something crucial ? Do I need to write some code to get the groups perms in my user perms ? I am using the base: django admin django users django perms In a second time, I would like this group to have access to add, edit, delete my models but not be able to see users, groups and permissions