Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to implement httponly jcookies with simple jwt django rest framework
is it possile to include httponly cookies in simple jwt django rest framework ? Serializers.py class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): # The default result (access/refresh tokens) data = super(CustomTokenObtainPairSerializer, self).validate(attrs) # Custom data you want to include data.update({'email': self.user.email}) data.update({'id': self.user.id}) data.update({'status':"success"}) # and everything else you want to send in the response return data Vies.py class CustomTokenObtainPairView(TokenObtainPairView): # Replace the serializer with your custom serializer_class = CustomTokenObtainPairSerializer -
How to create two models at once in django
I am making an API using DRF. Here I have a model called Blog and a model that refers to a Blog called Comment. When I create a Blog, I want to create several comments at the same time. Here's my current code. serializers.py class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' class BlogSerializer(serializers.Serializer): ... comments = serializers.ListField(child=serializers.DictField()) ... def create(self, validated_data): blog_validated_data = validated_data.copy() blog_validated_data.pop('comments') qs = Blog.objects.create(**blog_validated_data) comments = validated_data.get('comments') serializer = CommentSerializer(data=comments, many=True) serializer.is_valid(raise_exception=True) serializer.save() return qs models.py class Blog(models.Model): ... class Comment(models.Model): ... blog = models.ForeignKey(Blog, on_delete=models.CASCADE) ... How can I solve this code using queryset alone? -
Django Password Reset Confirm error (custom user model); update
I am not that experienced writing Python/Back-end, but trying to improve. In development/localserver I am trying to create a password reset form... but I got the following error when accessing the link from the forgot password email - and before that the password was not saving: init() missing 1 required positional argument: 'user' forms.py (almost copy/paste from Django's form; minor changes) class ResetPasswordForm(SetPasswordForm): error_messages = { 'password_mismatch': static_textLanguage['page_user_passwordReset_alert_passwordNotMatch'], 'password_empty': static_textLanguage['global_alert_mandatoryField'], 'minimum_length': static_textLanguage['global_alert_minCharacters_password'], } new_password1 = forms.CharField( required=False, widget=forms.PasswordInput(attrs={ 'id': 'page_userPasswordReset_content_form_input_passwordA', 'maxlength': '25', 'class': 'global_component_input_box' }), ) new_password2 = forms.CharField( required = False, widget=forms.PasswordInput(attrs={ 'id': 'page_userPasswordReset_content_form_input_passwordB', 'maxlength': '25', 'class': 'global_component_input_box' }), ) def __init__(self, user, *args, **kwargs): self.user = user super(ResetPasswordForm, self).__init__(user, *args, **kwargs) def clean_new_password1(self): password1 = self.cleaned_data.get('new_password1') if password1 == '' or password1 is None: raise forms.ValidationError(self.error_messages['password_empty'], code='password_field_empty') elif len(password1) < 8: raise forms.ValidationError(self.error_messages['minimum_length'], code='password_too_short') return password1 def clean_new_password2(self): password1 = self.cleaned_data.get('new_password1') password2 = self.cleaned_data.get('new_password2') if password2 == '' or password2 is None: raise forms.ValidationError(self.error_messages['password_empty'], code='password_field_empty') if password1 and password2: if password1 != password2: raise ValidationError(self.error_messages['password_mismatch'], code='password_mismatch') password_validation.validate_password(password2, self.user) return password2 def save(self, commit=True): password = self.cleaned_data["new_password1"] self.user.set_password(password) if commit: self.user.save() return self.user views.py class UserPasswordResetView(auth_views.PasswordResetConfirmView): template_name = '../frontend/templates/frontend/templates.user/template.page_passwordReset.html' form_class = ResetPasswordForm post_reset_login = True success_url = reverse_lazy('page_userLoginPrivate') def … -
From UML diagram to Django model and schemas
I am confused here to convert this uml diagram into django models/schemas. Can anyone help me out there? -
how to convert single array list form multiple array [duplicate]
how to convert single array list form one multiple array list in django For example x = [[1,2,3],[4,5,6],[6,7]] I need result like this x = [1,2,3,4,5,6,6,7] -
How to load chart in Django Template
I have an Altair chart which I want to render in a Django Template. The chart is converted into a json object in the views. Here is the code views.py def home(request): if request.method=='POST': year = request.POST['year'] df, cus_dict = generate_df(year) bar_obj = barGraphAltair(year, df) bar_obj = json.loads(bar_obj.to_json()) print(bar_obj) context = {'bar': bar_obj} return render(request, 'index.html', context=context) return render(request, 'index.html') template <div id='altair-viz'> {% if bar %} {{ bar|safe }} {% endif %} </div> This just prints the json in the template. I know I have to use Vega to render the graph but I am not sure how to do that in jinja syntax A temp solution One way I got this to work, is by creating a different view and calling that view in the template as follows views.py def renderAltair(request): df, cus_dict = generate_df('2017') bar_obj = barGraphAltair('2017', df) bar_obj = json.loads(bar_obj.to_json()) return JsonResponse(bar_obj) template <script> vegaEmbed('#altair-viz', "{% url 'altair' %}") </script> This works, but as you can see from the original code, I get the year by submitting a form and passing that to the function for generating the graph. So I need the graph to be created in the home view -
How to change the language based on user choice?
I translated my site using Rosetta. I have two languages; en and tr. I created a language field in my UserProfile model, and I created a button in navigation bar for changing user's language choice. What I want is; User's language choice will be the language of the website. For example; When user click the TR button, re_path turns http://127.0.0.1:8000/tr/ or user click EN button re_path turns http://127.0.0.1:8000/en/ in every page. How can I do that? urls.py urlpatterns += i18n_patterns( re_path('', include('customer.urls')), re_path('', include('register.urls')), re_path('', include('approvals.urls')), ) models.py class UserProfile(AbstractUser, UserMixin): username = models.CharField(max_length=500, unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) ... language = models.CharField(max_length=250) -
Reverse for 'edit-expense' with no arguments not found. 1 pattern(s) tried: ['edit\\-expense/(?P<id>[0-9]+)$'] - Django
Trying to display a Page to update record but receiving following error. ERROR NoReverseMatch at /edit-expense/2 Reverse for 'edit-expense' with no arguments not found. 1 pattern(s) tried: ['edit\\-expense/(?P<id>[0-9]+)$'] Request Method: GET Request URL: http://127.0.0.1:8000/edit-expense/2 Django Version: 3.2.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'edit-expense' with no arguments not found. 1 pattern(s) tried: ['edit\\-expense/(?P<id>[0-9]+)$'] Exception Location: C:\Users\Ideation\AppData\Roaming\Python\Python39\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Program Files\Python39\python.exe Python Version: 3.9.5 Python Path: ['C:\\xampp\\htdocs\\Projects\\Ideation\\Ideation', 'C:\\Users\\Ideation\\AppData\\Roaming\\Python\\Python39\\site-packages\\_pdbpp_path_hack', 'C:\\Program Files\\Python39\\python39.zip', 'C:\\Program Files\\Python39\\DLLs', 'C:\\Program Files\\Python39\\lib', 'C:\\Program Files\\Python39', 'C:\\Users\\Ideation\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Users\\Ideation\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32', 'C:\\Users\\Ideation\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32\\lib', 'C:\\Users\\Ideation\\AppData\\Roaming\\Python\\Python39\\site-packages\\Pythonwin', 'C:\\Program Files\\Python39\\lib\\site-packages'] Server time: Fri, 27 Aug 2021 05:30:22 +0000 views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .models import Category, Expense @login_required(login_url = "login") def expense_edit(request, id): expense = Expense.objects.get(pk=id) context = { 'expense': expense, 'values': expense, } if request.method == 'GET': return render(request, 'expenses/edit_expense.html', context) # if request.method == "POST": else: messages.add_message(request, messages.INFO, 'Handling post form') return render(request, 'expenses/edit_expense.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('add-expense', views.add_expense, name="add-expense"), path('edit-expense/<int:id>', views.expense_edit, name="edit-expense"), ] edit_expense.html {% extends 'base.html' %} {% block content %} <div class="container mt-4"> <h2>Edit Expense</h2> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="{% url 'index' %}">Expenses</a></li> <li … -
Select2 Django Multi-Select Select a valid choice. x is not one of the available choices
I currently am making my first form with Select2 that I am tying into a django form it throws me this error every time more than one item is selected Select a valid choice. ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'] is not one of the available choices. This is the exact error I get if I choose all options but if I choose two options I will only receive those 2 numbers in the list My current code for this form regarding this issue is as follows: forms.py class Meta: model = WebOrder fields = [ ... "overdenture_connections", ... ] ... OVERDENTURE_CONNECTIONS = (('2','2'),('3','3'), ('4','4'),('5','5'),('6','6'),('7','7'),('8','8'),('9','9'), ('10','10'),('11','11'),('12','12'),('13','13'),('14','14'), ('15','15'),('18','18'),('19','19'),('20','20'),('21','21'), ('22','22'),('23','23'),('24','24'),('25','25'),('26','26'), ('27','27'),('28','28'),('29','29'),('30','30'),('31','31')) overdenture_connections= forms.ChoiceField(choices=OVERDENTURE_CONNECTIONS,widget=s2forms.Select2MultipleWidget) models.py class WebOrder(models.Model): ... overdenture_connections = models.CharField(db_column="OverdentureConnections", max_length=128, null=True, blank=True) ... class Meta: db_table = 'WebOrders' htmlfile.html <form> {% csrf_token %} ... <div class="grid-x grid-padding-x" > <div class="cell small-12"> {{form.overdenture_connections.label_tag}}{{form.overdenture_connections}} </div> </div> ... </form> -
Removing labels from dynamic django crispy formset
I have a dynamic formset to allow users to add a variable number of entries. This is implemented using https://github.com/elo80ka/django-dynamic-formset, and outlined below This currently displays as:  And when a user adds another row as:  I would however like the labels to either be 1. removed entirely, or 2. only be present for the first row or 3. be within the entry box as opposed to above it? models.py class Patient(TimeStampedModel): # get a unique id for each patient - could perhaps use this as slug if needed patient_id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) class PastMed(TimeStampedModel): medication = models.CharField( “Medication”, max_length=20, default=‘unspecified’) dose = models.IntegerField("Dose (mg)", default=0) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) forms.py PastmedFormSet = inlineformset_factory( Patient, PastMed, fields=(“medication”, “dose”), extra=1) views.py class PatientAddView(LoginRequiredMixin,TemplateView): model = Patient template_name = "../templates/add.html" def get(self, *args, **kwargs): pastmed_formset = PastmedFormSet(queryset=PastMed.objects.none()) return self.render_to_response({'pastmed_formset': pastmed_formset}) add.html <script type="text/javascript" src="{% static 'js/jquery/dist/jquery.min.js' %}"></script> <script type="text/javascript" src="{% static 'js/jquery.formset.js' %}"></script> <script type="text/javascript"> $(function() { $('#pastmeds_table tbody tr').formset({ prefix: 'pastmed_set' }) }); </script> <div class="form-group"> <table id="pastmeds_table" border="0" cellpadding="0" cellspacing="5"> <tbody> {% for form in pastmed_formset %} <tr id="{{ form.prefix }}-row"></tr> <td> {% for fld in form.hidden_fields %}{{ fld }}{% endfor %} {% if form.instance.pk %}{{ form.DELETE … -
Getting KeyError when using request.session['role_type'] in django 3.0
urls.py urlpatterns = [ re_path(r'^jobs/week/$',login_required(JobWeekView.as_view()),name="job_week"), ] views.py class JobWeekView(View): def get(self, request): if request.session['role_type'] in [ClientUserRole.ROLE_JOBWORKER,ClientUserRole.ROLE_JOBWORKER_WITH_DOCS]: return redirect('crm:job_view') But I am getting error KeyError: 'role_type' . Here is full error traceback.Anyone pls help help me where I am wrong Traceback (most recent call last): File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/home/harika/lightdegreerespos/mcam/server/mcam/crm/views.py", line 9569, in get x = self.request.session['role_type'] File "/home/harika/lightdegree/lib/python3.7/site-packages/django/contrib/sessions/backends/base.py", line 64, in __getitem__ return self._session[key] KeyError: 'role_type' -
Delete an image completely in django gets SuspiciousFileOperation
I have a model with an ImageField and when the user changes the image I want the old image to be deleted from the media/ folder, it's from another answer on stackoverflow: def _delete_file(path): """ Deletes file from filesystem. """ if os.path.isfile(path): os.remove(path) @receiver(models.signals.post_delete, sender=User) def delete_file(sender, instance, *args, **kwargs): """ Deletes image files on `post_delete` """ if instance.image: _delete_file(instance.image.path) I also tried to delete old_image when new form is submitted: old_image = user.image old_image.delete(save=False) and this: fss = FileSystemStorage() fss.delete(old_image.url) I get SuspiciousFileOperation at / The joined path is located outside of the base path component How can I remove the image completely? -
django: no primary or candidate keys in the referenced table 'tcReports_global_users' that match the referencing column list in the foreign key 'fk
Here's my models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import UserManager class TcreportsGlobalApps(models.Model): appid = models.AutoField(db_column='appID', primary_key=True) # Field name made lowercase. path = models.TextField() name = models.TextField() stableversion = models.CharField(db_column='stableVersion', max_length=10) # Field name made lowercase. devversion = models.CharField(db_column='devVersion', max_length=10) # Field name made lowercase. apptype = models.CharField(db_column='appType', max_length=100, blank=True, null=True) # Field name made lowercase. appdepartment = models.CharField(db_column='appDepartment', max_length=100, blank=True, null=True) # Field name made lowercase. islive = models.BooleanField(db_column='isLive', blank=True, null=True) # Field name made lowercase. description = models.TextField(blank=True, null=True) class Meta: db_table = 'tcReports_global_apps' class TcreportsGlobalLog(models.Model): id = models.BigAutoField(primary_key=True) log = models.TextField() created_at = models.DateTimeField() class Meta: db_table = 'tcReports_global_log' class TcreportsGlobalPermissions(models.Model): appid = models.AutoField(db_column='appID', blank=True, primary_key=True) # Field name made lowercase. userid = models.IntegerField(db_column='userID', blank=True, null=True) # Field name made lowercase. permissions = models.BooleanField(blank=True, null=True) class Meta: db_table = 'tcReports_global_permissions' class CustomUserManager(UserManager): def create_user(self, username, password=None): if not username: raise ValueError('Users must have an username') user = self.model(username=username) user.set_password(password) user.save(using=self._db) user.userid = user.pk user.save() return user def create_superuser(self, username, password, email=None): user = self.create_user( username=username, password=password, ) user.is_superuser = True user.save(using=self._db) user.userid = user.pk return user class TcreportsGlobalUsers(AbstractBaseUser): userid = models.AutoField(db_column='userID', blank=True, primary_key=True) # Field name made lowercase. username = models.CharField(max_length=100, blank=True, … -
How to send data through jquery ajax properly in the backend?
Here I am getting trouble while submitting multiple input data .the data have same input names but with different group like this the group separates with q_title value. q_title=jjjjj&title=hhh&field_type=C&title=j&field_type=C&is_document_required=1 & q_title=jjjj&title=hh&field_type=C&is_document_required=1 . How can I send this type of data properly to the backend. I think want to send data by making a group that starts with q_title. Or what will be the best approach ? $(document).on('submit', '.form' ,function() { formdata = $(this).serialize() url = $(this).attr('action') console.log(formdata) $.ajax({ url: url, type: 'POST', data: new FormData(this), processData: false, contentType: false, success: function (data) { `formdata` is like this. `csrfmiddlewaretoken=djjrir0j7Efg0ipXkPxHiJIz9rYnAw2zj8tuxgmVe0HYgSbOfQWVZgSfblFwJZOX&q_title=jjjjj&title=hhh&field_type=C&title=j&field_type=C&is_document_required=1&q_title=jjjj&title=hh&field_type=C&is_document_required=1` -
How to hash the password using bcrypt in django?
I am converting php website to django. I have to match the password of a user during login. For hashing the password in cakephp Security::setHash('blowfish'); Security::setCost(7); Now I have to find same hashing function in django. I went through the this and found out that they use bcrypt to hash the password in CakePhp. I am beginner in Django and Can not figure out how to encrypt the password using bcrypt in Django specially setCost() function so that hashed password is same as in CakePhp. -
The first loading for a site was refused but freshing shows the website Django/Nginx/Gunicon/AWS Linux
The first loading for a site shows a connection refuse error. This site can’t be reached Xyz.com refused to connect. Try: • Checking the connection • Checking the proxy and the firewall ERR_CONNECTION_REFUSED Then, when I refreshed the site, the site is up and running. The tech stack for the site is on Django NginX Gunicorn AWS Ubuntu v18. This is a bit unusal, where can I start off to check the connection? -
Django reports that" NoReverseMatch at /"
When I learing Django, I wrote these code: In urls.py: In Views.py: In base.html: In Models.py: In topics.html: The Django report that NoRecerseMath at /, I have tried to use regx, replacing the re_path() with url() or path(), and rename the topics function. However, it does not work till now. Here is the full screenshop of the report. I'm really confusing with that, realllllly thanks for your help! -
Could not find the GDAL library in django. What can I do to resolve this problem?
I am working in django project and need to use PointField imported from django.contrib.gis.db.models. To use it, I installed GDAL by brew install gdal. When I enter gdal-config --version in terminal after installing it, I got the message 3.3.1. I believe this tells GDAL has been successfully installed. I also updated the database setting in settings.py like this. DATABASES = { 'default': { "ENGINE": "django.contrib.gis.db.backends.mysql", 'NAME': config("DB_PROD_NAME"), 'USER': config("DB_USER"), "PASSWORD": config("DB_PASSWORD"), "HOST": config("DB_HOST"), "PORT": config("DB_PORT") }, } And this is the models.py where PointField is used. from django.contrib.gis.db import models class Address(models.Model): address_name = models.CharField(max_length=100) address_name_detail = models.CharField(max_length=100) address_type = models.CharField(max_length=11) address_coord = models.PointField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: managed = False db_table = 'address' The problem is when I try python3 manage.py runserver or import the model Address in views.py, I get an error django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.2.0", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. By adding GDAL_LIBRARY_PATH = config('GDAL_LIBRARY_PATH') GEOS_LIBRARY_PATH = config('GEOS_LIBRARY_PATH') in settings.py, there is no longer error when I enter python3 manage.py runserver, but it is not the case in importing Address model. What … -
How is django's default root homepage rendered?
This is a kind of want-to-know itch. Many questions here ask how to replace the default Django homepage (e.g. ). I understand that issue. What I'm curious to know is how the default page is rendered when a new project is created (i.e., in debug mode). Even though my question is not as directly practical as knowing how to replace the default homepage, I have the feeling that if I figure it out, I may understand how Django works a bit better. I would expect it to be in the default urls.py file, but the only entry by default in urlpatterns of urls.py is path('admin/', admin.site.urls). My first naive expectation would be an entry in urlpatterns that you could remove or comment out. Since there's nothing there besides admin/, I'm guessing there's some other built-in app or middleware that specifies the default homepage, but I don't know where to look. Here's my progress in understanding this so far: Commenting out DEBUG=True in settings.py causes the default homepage to no longer appear. I've seen this documentation about how Django processes requests, which mentions middleware that can set the urlconf attribute on a request that changes the default, ROOT_URLCONF. So far Django … -
Passing Dropdown Choice to Modal Using Django For Loop
I have a dropdown with choices. The dropdown should be linked to a modal where I'd like to say "You selected Choice A" (or B or C), depending on what was clicked. I tried data-target="#myModal{{choice}}" and id="myModal{{choice}}", hoping that they would be linked, but with this, the modal won't show up at all. The modal appears when I remove {{choice}} though, but that's not what I want. Thanks for reading. Your help would be much appreciated. views.py: def modal_home(request): choices = [ "A", "B", "C" ] return render(request, 'modal/test-modal.html', { 'choices': choices, }) test-modal.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> </head> <body> <div class="dropdown"> <button class="btn dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown"> Create </button> <div class="dropdown-menu"> {% for choice in choices %} <a class="dropdown-item" href="#" data-toggle="modal" data-target="#myModal{{choice}}">{{ choice }}</a> {% endfor %} </div> </div> <div class="modal fade" id="myModal{{choice}}" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">MODAL</h5> <button type="button" class="close" data-dismiss="modal"> </button> </div> <p>Here I want to say "You selected Choice A"</p> </div> </div> </div> </body> </html> -
Fetching data from other website in django website and saved into our database
How I fetch data from one website to other website in django and stored into our database. -
Different queryset, same result
I'm currently learning Model Manager and Custom Queryset. While trying to understand the implementation of it, I somehow just don't get how the difference between these two calls. I like to include the all() because its more understandable. However I would like to know if there's any difference. 1. Post.objects.all().filter(status=1).order_by('-updated') 2. Post.objects.filter(status=1).order_by('-updated') >>> from django.contrib.auth.models import User >>> from blog.models import Post >>> user= User.objects.filter(username='chair').first() >>> Post.objects.filter(author= user) <PostQuerySet [<Post: 111 updateeee>, <Post: 22222>, <Post: draftdraft>]> >>> Post.objects.all().filter(author= user) <PostQuerySet [<Post: 111 updateeee>, <Post: 22222>, <Post: draftdraft>]> -
How to replicate "Available Groups" to "Chosen Group" functionality in Django Admin
I am moving from Rails to Django and trying to convert a Hamper Business website I run. Love Django!! I have hampers with a number of products. Each hamper has different products. I'd love to be able to use the following structure to move products into a hamper. An example: Django uses the following to have a list of groups which then moves to Chosen Groups: All I seem to be able to get with a ManyToManyField is a list box which I have to select by control and clicking to add multiple fields. This becomes impractical and not easy to read. To take it one step further, I'd love to be able to include a product more than once. For example, a hamper which has three bottles of the same beer. I would like to not have to set up three seperate products for the same hamper. Thanks so much in advance for pointing me in the right direction. -
Celery tasks get blocked by SSE client
I am running a SSE consumer in order to update a few tables like this @app.task(ignore_result=True) @worker_ready.connect def xx_sse_nodes_uptime_info_consumer(sender, **kwargs): update_tables... By some reason, other tasks are not triggered when we have a .delay calling other tasks. If I remove the task above, other tasks will work normally. Also, when CELERY_TASK_ALWAYS_EAGER=True and CELERY_TASK_EAGER_PROPAGATES=True everything runs fine. Since the SSE consumer uses stream=True the xx_sse_nodes_uptime_info_consumer never ends. I am not sure why this blocks others tasks tho as there are enough threads. -
How can I fix, "Failed lookup for key [name] in <URLResolver", on a django site that is hosted by a2hosting.com?
I am hoping to find someone that has django experience and also experience running a django site on a2hosting.com as that is the hosting i have. I originally set this up on my personal hosting there and the site is running just fine (just to make sure i could get it functioning before having the person im making it for buy their own hosting there.) I tried setting it up multiple times on the new hosting and i have been getting the 'Failed lookup for key [name] in <URLResolver' error. Most of the support i have found online suggests making sure all the names match across the url files and anywhere the app name is mentioned. Since i essentially copied and pasted this from a working copy on the same hosting service everything checks out. I am hoping someone with experience with a2hosting and django can offer any additional support or ideas as to how to fix this. it is currently throwing a 404 error saying: Using the URLconf defined in rextech.urls, Django tried these URL patterns, in this order: admin/ home/ The empty path didn’t match any of these. the error mentioned above appears in the django logs i …