Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redirect user to another form based on their response in the current form
My user is completing a sign up form. If they indicate that they are an 'expert'(choice field) in the form displayed using the SignUpView, I want them to be redirected to the ExpertInformationView, otherwise I want them to be redirected to my homepage. How can I do this? # views.py class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' class ExpertInformationView(FormView): template_name = 'info_form.html' form_class = ExpertUserInformationForm success_url = reverse_lazy('information') # models.py class CustomUser(AbstractUser): __USER_STATUS = [('Member', 'Member'), ('Expert', 'Expert')] user_status = models.CharField( max_length=20, choices=__USER_STATUS, default=__USER_STATUS[0], # 'Member' ) phone_number = models.CharField(null=True, blank=True, max_length=30) -
Is there a way to make a depend dropdown in django open edx registration?
i'm working in OpenEdx and i'm trying to make a registration page that contains custom fields, state and city. here is my models.py: class City(models.Model): name = models.CharField('city', max_length=100, blank=True) uf = models.CharField('UF', max_length=2, choices=STATE_CHOICES) def __str__(self): return self.name class Meta: ordering = ('name',) verbose_name = 'cidade' verbose_name_plural = 'cidades' class UserProfileExtras(models.Model): user = models.OneToOneField( USER_MODEL, null=True, on_delete=models.CASCADE ) state = models.CharField( verbose_name="State", choices=STATE_CHOICES, max_length=100, ) city = models.CharField( verbose_name="Cidade", choices=CITY_CHOICES, max_length=100, null=True, ) and forms.py: class UserProfileExtrasForm(ModelForm): class Meta(object): model = UserProfileExtras fields = ('state', 'city') def __init__(self, *args, **kwargs): super(UserProfileExtrasForm, self).__init__(*args, **kwargs) self.fields['state'].label = _(u"Estado") self.fields['state'].error_messages = { "required": _(u"Selecione seu Estado."), "invalid": _(u"Estado inválido."), } self.fields['city'].label = _(u"Cidade") self.fields['city'].error_messages = { "required": _(u"Selecione sua cidade."), "invalid": _(u"Cidade inválida"), } i want to make the city dropdown appears only the selected state's cities thanks -
The QuerySet value for an exact lookup must be limited to one result
hello guys iam having issue in the underlying section as iam tring to print this comment section my models.py file iam trying to get the detailed page of any single post which contains post and comment form and previous comments but i am getting this errorThe QuerySet value for an exact lookup must be limited to one result using slicing. from django.db import models class Category(models.Model): name=models.CharField(max_length=60) def __str__(self): return self.name class Post(models.Model): title=models.CharField(max_length=60) body=models.CharField(max_length=500) created_on = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) categories = models.ManyToManyField('Category', related_name='posts') def __str__(self): return self.title class Comment(models.Model): author = models.CharField(max_length=60) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) post = models.ForeignKey('Post', on_delete=models.CASCADE) def __str__(self): return self.body And my views.py file is from django.shortcuts import render from django.http import HttpResponse from .models import * from .form import CommentForm def blog_index(request): post=Post.objects.all().order_by('created_on') context={ 'post':post } return render(request,'blog/blog_index.html',context) def blog_detail(request,id): posts = Post.objects.filter(categories__name__contains=category).order_by('-created_on') form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment( author=form.cleaned_data["author"], body=form.cleaned_data["body"], post=posts ) comment.save() comments = Comment.objects.filter(post=posts) context = { "post": posts, "comments": comments, "form": form, } return render(request, "blog/blog_details.html", context) def category(request,Category): posts = Post.objects.filter(categories__name__contains=category).order_by('-created_on') context = { "category": category, "posts": posts } return render(request, "blog/blog_category.html", context) -
Django Admin Abstract Class
I have searched and come across answers for admin model for abstract database model. I am looking for abstract admin class, i.e. not database model class. I have some common admin functionality I wish to put in a abstract, class then inherit from it. Note: the getter_for_related_field is from https://github.com/PetrDlouhy/django-related-admin, since for some odd reason the Django team things foreign keys in list displays is a rare use case. class FactAdminAbstract(admin.ModelAdmin): foo__bar = getter_for_related_field( "foo__bar ", short_description="Foo Bar" ) foo__baz = getter_for_related_field( "foo__baz ", short_description="Foo Baz" ) date_hierarchy = "created" # Remove the delete selected bulk action def get_actions(self, request): actions = super().get_actions(request) if "delete_selected" in actions: del actions["delete_selected"] return actions @classmethod def build_list_display(cls, *custom): cls.list_display = ( "created", *custom, "foo__bar", "foo__baz", ) cls.list_display_links = cls.list_display @classmethod def build_list_filter(cls, *custom): cls.list_filter = ( "created_utc", *custom, "foo__bar", "foo__baz", ) Then trying to use it like: @admin.register(Cannon) class CannonAdmin(FactAdminAbstract): FactAdminAbstract.build_list_display('cannon_ball') FactAdminAbstract.build_list_filter('cannon_ball') @admin.register(Pogo) class PogoAdmin(FactAdminAbstract): FactAdminAbstract.build_list_display('pogo_stick') FactAdminAbstract.build_list_filter('pogo_stick') But then it seems like Django blurs the models, and combines the two instances that both inherit from the same abstract base class. <class 'CannonAdmin'>: (admin.E108) The value of 'list_display[1]' refers to 'pogo_stick', which is not a callable, an attribute of 'CannonAdmin', or an attribute or … -
How can I log local variables of the view function in Django when DEBUG is off?
I'm trying to implement something like Django's yellow exception HTML page, where it has the stacktrace, local and global variables. And I want to log that info to a file on production where DEBUG=False. I tried a custom middleware and only managed to log the stacktrace and the global variables, but most importantly I need to log the local variables of the views function or view class -
How to extract a variable from html(Jinja2) to python for modify a variable?
The situation is the next. I have a variable got from input in the html(jinja2) but I need to export it to python for change a variable that is in my python file. <input type="number" name="DateO"/> <input type="number" name="DateT"/> I want to take "DateO" and "DateT" for a python variable. pdt: I'm using Django -
Why is it not possible to use the AsyncClient to login without using sync_to_async?
According to the documentation about testing async functions in Django 3.1, it should be possible to simply await the async client methods in an async context without having to wrap it in sync_to_async or database_sync_to_async as it implements all methods. Is there a way around this? The first request works, but the second and third do not. class TestAsyncClient(TransactionTestCase): def setUp(self): self.async_client = AsyncClient() self.user = get_user_model().objects.create_user("user_a@example.com", "passwd_a") async def test_async_login(self): """Use the async client to login without using sync_to_async""" request = await self.async_client.get("/") self.assertTrue(request) logged_in = await self.async_client.login( username="user_a@example.com", password="passwd_a" ) self.assertTrue(logged_in) logged_in = await self.async_client.force_login(self.user) self.assertTrue(logged_in) -
Add user group as class name to body tag? Django/Wagtail
Is there a way of editing the body tag classes so that when each user logs in their group name is included in the html body class name. I want to do this so i can edit fields and permissions with javascript as some features that i need are not possible with standard Wagtail. Thanks -
How to create dict in django model having same brokers who having diffrenet boats?
Models.py :. class Match(models.Model): rep_broker = models.ForeignKey('account.User', related_name='rep_broker',on_delete=models.CASCADE,blank=True,null=True) boat = models.ForeignKey('boat.Boat', related_name='matches', on_delete=models.CASCADE) How to query the Match model to get the output like "rep_broker have 3 boats matching" table example: broker1 | boat1 broker1 | boat2 broker2 | boat3 output : broker1 have 2 boats matching broker2 have 1 boat matching Output should be in dictionary. -
How to run django_cron from crontab
With the below command, I am trying to run django_cron from the CLI (as it is not working from crontab). sudo -u www-data /path/to/venv/bin/python3 /path/to/web/manage.py runcrons my_custom_app.cron.myCronCommand --force --settings=mysite.settings.dev Annoyingly though, it is telling me that it cannot connect to an sqlite database, this is even though my sites base.py settings files (which dev inherits) is using mysql (and the browser shows it working just fine). So I imagine I must be not using the --settings command correctly, as I would have thought that this command would tell it to use the file in mysite/settings/dev.py. Any pointers would be greatly appreciated. -
Django 3.1.1 Static files Not Found
Currently having an issue where my static resources aren't loading after I host on Heroku. This is the error I'm getting: DevTools Error My urls.py: urlpatterns = [ path('', include('doppelganger.urls')), path('admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "doppelganger/static"), ] Directory structure: project setting.py urls.py wsgi.py doppelganger static js img css Django version: 3.1.1 Python version: 3.8.6 I have tried running python manage.py collectstatic and I'm still seeing the same errors. Any other suggestion I can try to help fix "GET /static/css/beta_main.css HTTP/1.1" 404 Not found ? -
How can I get all results containing elasticsearch-dsl query keyword?
When I query my PostDocument it returns the results that only contain full words from the query. For example if there were 4 posts: "Post 1" "Post 2" "Posts 3" "Po 4" and I query it with: posts = PostDocument.search().query('match', body="Post") it will return items 1 and 2, if body="Po" it will return only item 4. How can I write the query so it returns all the results that contain the keyword? For example if I did this body="Po" I would get all 4 items. -
PostListView is missing a QuerySet. Define PostListView.model, PostListView.queryset, or override PostListView.get_queryset()
I am facing this error i need help. I am trying to add two models in a single class view to be displayed in a same template here is my django view code. class PostListView(ListView): template_name = 'blog/videography.html' ordering = ['-date_posted'] paginate_by = 5 def get_context_data(self, **kwargs): context = super(ProjectListView, self).get_context_data(**kwargs) context['videosleft'] = VideoLeft.objects.all() context['videosright'] = VideoRight.objects.all() return context def videography(request): context = { 'videosleft': VideoLeft.objects.all(), 'videosright': VideoRight.objects.all() } return render(request, 'blog/videography.html', context) here is my django model code. class VideoLeft(models.Model): titlel = models.CharField(default='Enter A Name Identification !', max_length=200) linkleft = models.URLField(max_length=1000) contentleft = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.titlel def get_absolute_url(self): return reverse('video-detail', kwargs={'pk': self.pk}) class VideoRight(models.Model): titler = models.CharField(default='Enter A Name Identification !', max_length=200) linkright = models.URLField(max_length=1000) contentright = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.titler def get_absolute_url(self): return reverse('video-detail', kwargs={'pk': self.pk}) here is my django url code. here is my django url code. here is my django url code. here is my django url code. here is my django url code. urlpatterns = [ path('', views.home, name='blog-home'), # path('video/<int:pk>/', PostDetailView.as_view(), name='video-detail'), path('video/new/', PostCreateView.as_view(), name='video-create'), path('video/<int:pk>/update/', PostUpdateView.as_view(), name='video-update'), path('video/<int:pk>/delete/', PostDeleteView.as_view(), name='video-delete'), path('photography/', views.photography, name='blog-photography'), path('articles/', views.articles, name='blog-articles'), … -
how can I use foreign key to import users login from google by Django-allauth
I am using 2 login methods, one is Django inbuilt authentication and another by using "allauth" of google. I want to make a separate model with only the entries from google logged-in people by using a "foreign key" and few more attributes. In Django admin page there is a table "Social accounts", which has only google logged in users, so how can I include that model? -
I am unable to create a new custom user in Django
I tried creating a new user but it didn't work, I have tried debugging it but don't get a way about this, kingly help. I have a User Model but want to try and create different user types like students, teachers something like that which would all be in the user user model as well as their various user models. View.py def AddCustomerManager(request): if request.method == "POST": email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') try: user = User.objects.create_user(email=email, username=username, password=password, user_type=2) user.save() messages.success(request, "Customer Manager Added Successfully") except: messages.error(request, "Failed to Add Customer Manager") return render(request, "pusheat_admin/addcm.html") models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) user_type_choice = ((1, "SuperUser"), (2, "CustomerManager")) user_type = models.CharField(default=1, choices=user_type_choice, max_length=10) objects = UserManager() class CustomerManager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=50, blank=False) email = models.EmailField() password = models.CharField(max_length=32) addcm.html <form role="form" method="POST"> {% csrf_token %} <div class="card-header"><h4>Add Customer Manager</h4></div> <div class="card-body"> <div class="form-group"> <label>Email address</label> <input type="email" class="form-control" name="email" placeholder="Enter email"> </div> <div class="form-group"> <label>Username</label> <input type="text" class="form-control" name="username" placeholder="Username"> </div> <div class="form-group"> <label>Password</label> <input type="password" class="form-control" name="password" placeholder="Password"> </div> </div> <div class="card-footer"> <button type="submit" class="btn btn-primary">Add Customer Manager</button> </div> </form> -
Django button not toggling
I have a button on a page that I want to toggle back and forth between "Follow (+)" and "Following". For some reason it is not toggling at all and I'm really struggling to understand why. The button is doing what I want it to do in terms of adding/removing the user to/from the profile followers so I know the button is working but the text of the button is not changing. views.py def profile_page(request, user_username): currentUser = request.user profile = get_object_or_404(User, username=user_username) if profile.followers.filter(user=currentUser).exists() == True: a_follower = True else: a_follower = False return render(request, "network/profilePage.html", { "profile": profile, "currentUser": currentUser, "a_follower": a_follower }) profilePage.html {% if currentUser != profile %} <form action="{% url 'follow' profile.username %}" method="POST"> {% csrf_token %} <input type='hidden' name='profile_id' value="{{ profile.id }}"> {% if currentUser is a_follower %} <input type="submit" value="Following"> {% else %} <input type="submit" value="Follow (+)"> {% endif %} </form> {% endif %} Can anyone see what the problem is? Please let me know if I need to include more details. -
How can i create stream follow date in logger Django?
Currently, i'm using watchtower and boto3 to create and handle logs from Django to Cloudwatch AWS, but i want to auto create stream_name follow date, how can i do it? This is my code: def check_log(request): logger_boto3_session = boto3.Session( aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['SessionToken'], region_name=AWS_DEFAULT_REGION) logging.basicConfig(level=logging.DEBUG) cw_handler = watchtower.CloudWatchLogHandler(log_group="log-app-atbb", stream_name=datetime.now().strftime('%Y-%m-%d'), boto3_session=logger_boto3_session) logger = logging.getLogger('watchtower') logger.info("Hello World") In my code, it only create one time is current date, tomorrow, it can't create new log stream with tomorrow date on Cloudwatch Expect: Today: 11/03/2020 -> create log stream is 2020-11-03 Tomorrow: 12/03/2020 -> will auto create log stream is 2020-12-03 -
File Upload Only Works Sometimes in Django
I am trying to upload text files which get converted into csvs and then into my database. However, the file upload only works when I have created the text file in my project directory. For example, when I have a text file that I create here it works - I can drag this file into my template with the upload files button and it makes the rows in the database. When I create the test.txt file on my desktop and try to import the file in my template, nothing happens and it returns an empty csv file. Views.py @login_required(login_url='login') def upload(request, *args, **kwargs): if request.method == "GET": return render(request, 'users/upload.html') if request.method == "POST": # Create subject object in database cram_set = CramSet.objects.create( subject='Other', name='', ) raw_file = request.FILES['file'] contents = raw_file.read().decode('UTF-8') question_pattern = re.findall( r'^\d+\)\s*((?:(?:(?!^\d+\))[\s\S])*?\n(([A-Z])\)(?:(?!^\d+\))[\s\S])*?)$)?(?:(?!^\d+\))[\s\S])*?)\nAnswer:\s*(\3|FALSE|TRUE)\nExplanation:\s*(.*)', contents, re.M) df = pd.DataFrame(question_pattern, columns=["Question", "Answer", "1","2","Explanation"]) clean_df = df.drop(columns=["1", "2"]) data_set = clean_df.to_csv(index=False) io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar='"',quoting=csv.QUOTE_MINIMAL): _, created = Question.objects.update_or_create( question=column[0], answer=column[1], explanation=column[2], cram_set_id=cram_set.pk, ) return redirect('/users/' + request.user.username + '/') return render(request, 'users/upload.html') Do I need to save these files in a Media file in my project so that I can work with them … -
Converting from Raw Sql to Django Queryset API
I am currently doing a sample profile information with total counts of friends. It is actually working fine with raw sql, and I read a lot that it is highly recommended to use Django ORM than using raw sql. I tried several ways such as implementing with aggregate() or annotate() but none of those ways seem to work base on my expected result. Any help would mean very much to me. Thanks in advance! Here are my models: Profile class Profile(models.Model): user = models.ForeignKey(User, related_name="profile", on_delete=models.CASCADE, null=False) mobile_no = models.CharField(max_length=20, null=False, unique=True) first_name = models.CharField(max_length=30, null=False) last_name = models.CharField(max_length=30, null=False) gender = models.CharField(max_length=20, null=False) objects = ProfileManager() class Meta: db_table = 'profile' Friends class Friend(models.Model): to_user = models.ForeignKey(AUTH_USER_MODEL, models.CASCADE, related_name="friends") from_user = models.ForeignKey( AUTH_USER_MODEL, models.CASCADE, related_name="_unused_friend_relation" ) created = models.DateTimeField(default=timezone.now) objects = FriendshipManager() class Meta: db_table = 'friends' Here is my raw query written in ProfileManager() and ProfileQuerySet() class ProfileQuerySet(models.QuerySet): def get_complete_user_profile(self, user_id): user_profile_query = self.raw("""select profile.*, (select count(*) from friend where friend.from_user_id = profile.user_id) as friends from profile where user_id = %(id)s""", params={'id': user_id}) return user_profile_query class ProfileManager(models.Manager): def get_queryset(self): return ProfileQuerySet(self.model, using=self._db) def user_profile(self, user_id): return self.get_queryset().get_complete_user_profile(user_id=user_id) -
Django Permission classe gets called twice
i'm facing an odd problem in my project. I have created a simple custom permission class to understand how the system works. class CustomPermission(permissions.BasePermission): def has_permission(self, request, view): print("something") return True When I try add this permission to an APIVIew in the terminal "something" prints twice. Is it normal for a view to check permission two times for the same request? -
Django annotate sort by
i need your help. i have two models candidate/models.py class Candidate(models.Model): skill = models.TextField(blank=True) and employer/models.py class Job(models.Model): skill = models.TextField(blank=True) and i need to sort based on this two, in another views interview/views so i need a query set to sort this. Interview models have a job and candidate as their foreign key class Application(models.Model): candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE) job = models.ForeignKey(Job, on_delete=models.CASCADE) can anyone help me out? i've been stuck with this for days. Application.objects.annotate(percentage=(Count('candidate__skill', filter=Q(candidate__skill__in=job__skill)) / Count('job__skill') * 100 )).order_by() this code above, have an error in candidate__skill__in=job__skill Thank you! -
get_absolute reverse URL multi Slug Many To Many Field Django Model
I use Slugs to address the URL. It all works but when I want to show product details. I don't know how can I get two slugs from another model and put it beside the details slug. (the category is in the main URL) (show me all products Samsung mobile) Works: site.com/category/mobile/samsung/ (I want when I want to click one of them, show me the details, but it doesn't work) Doesn't Work: site.com/category/mobile/samsung/s10 Model: from Django.db import models from Django.shortcuts import reverse class Category(models.Model): name = models.CharField(max_length=150) slug = models.SlugField(unique=True, max_length=200) child_category = models.ForeignKey('self', max_length=150, null=True, blank=True, on_delete=models.CASCADE) is_child = models.BooleanField(default=False) def get_absolute_url(self): return reverse('shop:brands', args=[self.slug]) def get_absolute_url_product(self): return reverse('shop:products', args=[self.child_category.slug, self.slug]) class Product(models.Model): category = models.ManyToManyField(to=Category, related_name='products') name = models.CharField(max_length=150) slug = models.SlugField(unique=True, max_length=200) description = models.TextField() # Here I did what I knew, but It didn't work. =============================================== def get_absolute_url_details(self): return reverse('shop:product_details', self.category.model.slug, self.category.model.child_category.slug, self.slug) When I use this reverse way, it gives me this Error: 'ForwardManyToOneDescriptor' object has no attribute 'slug' URL: from Django.urls import path from Shop import views app_name = 'shop' urlpatterns = [ path('<slug:brands_slug>/', views.brands, name='brands'), path('<slug:brands_slug>/<slug:product_slug>/', views.products, name='products'), path('<slug:brands_slug>/<slug:product_slug>/<slug:product_details>/', views.details_products, name='product_details'), ] View: def products(request, brands_slug, product_slug): product = Product.objects.filter(category__slug=product_slug, category__child_category__slug=brands_slug) context = … -
How to filter a serializer manytomany field in djangorestframework
I want to filter the manytomany field based on the current instance selected field['customer']. I want the cart_items manytomany field to only contain the cart_items of the selected customer in cart API. models.py class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product_id = ShortUUIDField(unique=True, editable=False) name = models.CharField(max_length=100) # price = MoneyField(max_digits=14, decimal_places=2) price = models.DecimalField(max_digits=14, decimal_places=2) class Customer(models.Model): customer_id = ShortUUIDField() user = models.ForeignKey(User, on_delete=models.DO_NOTHING) name = models.CharField(max_length=255, blank=False) email = models.EmailField(unique=True) class CartItems(models.Model): cart_items_id = ShortUUIDField() user = models.ForeignKey(User, on_delete=models.DO_NOTHING) customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING) products = models.ForeignKey(Product, on_delete=models.DO_NOTHING) quantity = models.IntegerField(default=1) class Meta: unique_together = ( ("customer", "user", "products"), ) class Cart(models.Model): cart_id = ShortUUIDField() user = models.ForeignKey(User, on_delete=models.DO_NOTHING) customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING) cart_items = models.ManyToManyField(CartItems) serializers.py class CartSerializer(serializers.ModelSerializer): class Meta: model = models.Cart fields = '__all__' read_only_fields = ['user'] I have tried to use all of the things below. Any help would be appreciated. Requirement: The cart_items must contain items of the selected customer only. class CartSerializer(serializers.ModelSerializer): """serializer for Product objects.""" # authors = serializers.PrimaryKeyRelatedField(queryset=Author.objects.all(), many=True) # cart_items = serializers.PrimaryKeyRelatedField(queryset=models.CartItems.objects.filter(customer=self.context['request'].user), many=True) # cart_items = serializers.PrimaryKeyRelatedField(queryset=models.CartItems.objects.filter(user=2), many=True) # cart_items = CustomerFilteredPrimaryKeyRelatedField(many=True, source='user.Customer') # cart_items = serializers.PrimaryKeyRelatedField('get_cart') # # def get_cart(self, product): # qs = models.CartItems.objects.filter(user=2) # serializer = CartItemSerializer(instance=qs, many=True) … -
django console.log in script tag not working
Only a script a tag in html, not log in console index.html <script> console.log(123) </script> urls.py path('', TemplateView.as_view(template_name='index.html')) -
How do I run my django server from pycharm?
im wondering how I run django server from pycharm? I dont know where I should run it. Does someone know? Beginning programmer