Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model field validators doesn't work at all
I can't figure out why my validators doesn't work at all. Form is not invalid Model doesn't raise ValidationError when being saved For input: "123456sdad" I have a model which has broker_ico field: REGEX_ICO = r"\d{6,8}" broker_ico = models.CharField(max_length=100, verbose_name='IČO', validators=[RegexValidator(REGEX_ICO)]) I've overwritten save method: def save(self, **kwargs): print('full clean') self.full_clean() super().save(**kwargs) Moreover the form is a ModelForm: class BusinessCaseDocumentForm(ModelForm): class Meta: model = BusinessCaseDocument exclude = ['id','business_case'] def __init__(self, *args, **kwargs): super(BusinessCaseDocumentForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): fs_helpers.add_widget_attribute('class', 'form-control', field) UpdateView: class BusinessCaseDocumentUpdateView(SuccessMessageMixin, UpdateView): model = BusinessCaseDocument form_class = BusinessCaseDocumentForm template_name = "business_cases/businesscase_documents/create.html" success_message = "Podklad k obchodnému prípadu bol upravený" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['businesscase'] = self.object.business_case # TODO self.businesscase set return context def get_success_url(self): return reverse("business_cases:list") Can you see where is the problem? -
Django Mysql Intersections
My table with this values on Django 1.11: id, product, category 1, A, 1 2, B, 1 3, B, 2 4, C, 1 5, C, 2 6, D, 2 7, E, 2 8, E, 3 9, F, 3 10, F, 4 I need to select only products matching category (1 OR 2) AND category (3 OR 4) in Django. Expected result is only product: E. Because E has category 2 and 3. cat 2 is on array (1,2) and cat 3 is on array (3,4). I have error "intersections are not supported in mysql" How i can achieve this using Q() ? This query return zero objects. main_query = Q() main_query &= Q(category__in=[1,2]) main_query &= Q(category__in=[3,4]) models.Table.objects.filter(main_query) Any suggestions? -
How to retain search filters in second page in django tables2
I am facing a problem in applying search in django tables2, actually i have created a search filter and applying on the django orm and passing it into configure() function of django tables2 with pagination applied, but whenever i press next page, value of search filter empties and search does not works. Could anybody suggests me a way to retain value of search value whenever i press next button. My Views.py file def coupons(request): search_filter = {} form = CouponSearchForm() if request.POST.get('active'): active = True if request.POST['active'] == 'true' else False search_filter['active'] = active if request.POST.get('marketing'): active = True if request.POST['marketing'] == 'true' else False search_filter['marketing'] = active if request.POST.get('coupon_code'): search_filter['code__icontains'] = request.POST.get('coupon_code') if request.POST.get('created_by'): if request.POST.get('created_by') in User.objects.all().values_list('username', flat=True): search_filter['created_by_id__username'] = User.objects.get(username=str(request.POST.get('created_by'))) else: search_filter['created_by_id'] = int(0) if request.POST.get('language') and request.POST.get('language') != '': search_filter['language__pk'] = request.POST.get('language') if request.POST.get('package_id') and request.POST.get('package_id') != '': search_filter['package_id__pk'] = request.POST.get('package_id') if request.POST.get('email') and request.POST.get('email') != '': search_filter['email__icontains'] = request.POST.get('email') if request.POST.get('phone_number') and request.POST.get('phone_number') != '': search_filter['phone_number__icontains'] = request.POST.get('phone_number') if request.POST.get('exam_type') and request.POST.get('exam_type') != '': search_filter['exam_type__pk'] = int(request.POST.get('exam_type')) if request.POST.get('exam_name') and request.POST.get('exam_name') != '': search_filter['exam_name__exam_name'] = ExamName.objects.get(id=int(request.POST.get('exam_name'))).exam_name table = CouponTable( Coupon.objects.filter(**search_filter).order_by('-updated_at')) RequestConfig(request, paginate={"per_page": 30}).configure(table) return render(request, 'common/table.html', {'table': table, 'model': 'Coupon', 'url': 'add_coupon', 'form': form}) as … -
project may not work properly until you apply the migrations for app(s) but migrations doesn't work
I'm trying to run a panel on local. this error shows up when I run server: You have 149 unapplied migration(s). Your project may not work properly >until you apply the migrations for app(s): account, admin, authtoken, >conf, easy_thumbnails, finance, messaging, order, payment, product, >sites, warehouse. Run 'python manage.py migrate' to apply them.```` I also tried this: python3.6 manage.py makemigrations it says: No changes detected and finally when I use migrate command it says: AttributeError: 'DatabaseOperations' object has no attribute >'geo_db_type' -
How to post multipart/form-data from angular to Django REST API
I'm using Django REST API and Angular 6 for the frontend. I have defined an ImageField in the Profile model which accepts File input. In angular application, I'm generating File object from the Base64 image data and sending to the endpoint with header as Content-Type: 'multipart/form-data' The data sent is where first_name and profile.avatar are the form fields and profile.avatar contains the image file. But in the network tab the parameters sent for profile.avatar is empty dictionary. How can I send media file as form-data from Angular to REST API? -
How to upgrade to Django 2: ModuleNotFoundError: No module named 'django.urls'
I was using Django 1.9 and upgraded to Django 2.0 as follows: pip install -U django The main reason to updated django was the usage of path. As far as I understand, path is unavailable in Django 1.9. So, I have this import in my code: from django.conf.urls import url from django.urls import path # !!! this line fails !!! from django.contrib import admin from crida_airports import views urlpatterns = [ url(r'^admin/', admin.site.urls), path("test", views.test_endpoint, name='test_endpoint'), url(r'', 'my_tests.views.index'), ] However when I run the code, it throws the following error: ModuleNotFoundError: No module named 'django.urls' It looks like it is still using an old version of django. How to solve this error? How should I upgrade to Django 2 or how can I use something similar to path in Django 1.9? -
How to get the relative path of files in the django ListAPIView?
Want a relative path of the image to be returned from the API: Want "/media/image.jpg" format, not "http://0.0.0.1:8000/media.image.jpg" to be returned for the API For the following, getting full URL i.e. "http://0.0.0.1:8000/media.image.jpg" format class ImageListAPIView(ListAPIView): serializer_class = QuestionImageSerializer queryset = QuestionImage.objects.all() And for the following, getting correct output i.e.: media/image.jpg format, which is required. class ImageAPIView(APIView): def get(self, request, format=None): QuestionImages = QuestionImage.objects.all() SerializedData = QuestionImageSerializer(QuestionImages, many=True) return Response({ 'QeustionImages:': SerializedData.data }) How to return the relative path URL for the ListAPIView? Tried putting following in the serializer, but then not able to upload the image to the API. image = serializers.SerializerMethodField() def get_image(self, obj): return obj.image.url PS: models.py: class QuestionImage(models.Model): image = models.ImageField(upload_to=question_directory_path) serializers.py: class QuestionImageSerializer(ModelSerializer): class Meta: model = QuestionImage fields= [ 'id', 'image', ] -
Django - How do you assign 'feedback' for each 'user' to a single 'assignment'? (Many to one)
I have three models 'User', 'Assignment' and 'Feedback'. I am trying to setup a OneToMany assignment that can be accessed/viewed by all user accounts, where feedback can then be applied but only viewed by a OneToOneField user account. Here is some code to help explain what is currently happening. from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save # Create your models here. class UserProfile(models.Model): USER_TYPE_CHOICES = ( ('Student', 'Student'), ('Lecturer', 'Lecturer'), ('Admin', 'Admin'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) uni_id = models.IntegerField(default=0) type_user = models.CharField(max_length=20, default='s',choices=USER_TYPE_CHOICES) description = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') website = models.URLField(default='') phone = models.IntegerField(default=0) image = models.ImageField(upload_to='profile_image', blank=True) def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) # Assignment model class Assignment(models.Model): assignment_title = models.CharField(max_length=256) assignment_id = models.IntegerField(default=0) user = models.ManyToOneField(User, on_delete=models.CASCADE) # Feedback model class Feedback(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) I thought about maybe a foreign key connecting the assignments to a OneToOne field in the feedback model, but I'm really not sure. Any help would be greatly appreciated. -
django-environ DATABASE_URL format
I am using django-environ in my project alongside with postgresql. I have been searching through the docs and found the format for DATABASE_URL to be like this: DATABASE_URL=psql://user:password:port@database_url/db_name However, by doing so the output of env.db('DATABASE_URL') is {'PASSWORD': '', 'HOST': 'user', 'PORT': password, 'NAME': '', 'USER': '', 'ENGINE': 'django.db.backends.postgresql'} What am I doing wrong here? -
Not saving user to database immediately
I am having an issue where after a user signs up, they are redirected to a dashboard view that has @login_required; however, they cannot access it because the user gets saved to my database after 30 seconds for some reason, not instantly. I am wondering how I can sign up a user, and instantly save them so that they pass the @login_required field and can be properly redirected to the dashboard. Signup view def teacher_sign_up(request): form = TeacherSignUpForm(request.POST) if request.method == 'POST': form = TeacherSignUpForm(request.POST, request.FILES) if form.is_valid(): user = form.save() return redirect('/teacher/dashboard') else: messages.error(request, 'Make sure all your information is valid') else: form = TeacherSignUpForm() context = {'form' : form} return render(request, 'accounts/teacher_sign_up.html', context) Dashboard view @login_required def dashboard(request): return render(request, 'teacher/dashboard.html') -
Swagger prints only string datatype in Django Rest Framework using DefaultRouter
I'm struggling with generating documentation (or simply - with whole project). I'm barely new to Django and Python, so maybe my problem is quite trivial. I've got bunch of well defined models in Django Rest Framework project, for working with them I'm using DefaultRouters - the project is starting now and is in the early phase of development. However, for have all actions listed, I've managed to install Swagger and run it. My problem is, that Swagger in all actions, in almost all parameters prints "string" data type. For example: Model class UseCaseVer(models.Model): id = models.IntegerField(primary_key=True), version_key = models.CharField(max_length=10,null=False,unique=True) approv_date = models.DateField(default=timezone.now,null=False) description = models.TextField() class Meta: abstract = False Serializer: class UseCaseVerSerializer(serializers.ModelSerializer): date_joined = serializers.DateTimeField() class Meta(object): model = UseCaseVer fields = ('id', 'version_key', 'approv_date', 'description') Still gives me string in all fields. What is wrong? -
Django : CSRF verification failed. request aborted
I'm currently viewing Django documentaion for creating a Form with post method(https://docs.djangoproject.com/en/2.1/intro/tutorial04/). But, I get a CSRF verification failed. Request aborted error while executing the vote() function in views.py files being used are: views.py: from django.http import HttpResponse, Http404 from django.shortcuts import render, get_object_or_404 from django.urls import reverse from .models import Question . . . def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk = request.POST['choice']) except (KeyError, choice.DoesNotExitst): return render(request, 'polls/detail.html',{ 'question': question, 'error_message': "you didn't select a choice" }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args= (question.id))) detail.html: <h1>{{ question.question_text }}</h1> {%if error_message%}<p><strong>{{error_message}}</strong></p>{%endif%} <form action="{%url 'polls:vote' question.id%}" method="post"> {% csrf_token %} {%for choice in question.choice_set.all%} <input type = "radio" name = "choice" id="choice{{ forloop.counter }}" value = "{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{choice.choice_text}} </label><br> {%endfor%} <input type="submit" value="vote"> </form> results.html: <h1>{{ question.question_text }}</h1> <ul> {%for choice in question.choice_set.all%} <li>{{choice.choice_text}} -- {{choice.votes}} vote{{choice.votes|pluralize}}</li> {&endfor&} </ul> <a href="{%url 'polls:detail question.id'%}">Vote again?</a> these are the MIDDLEWAREs used: `MIDDLEWARE = [ 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] yet I get this error: -
Error in locating and reading specific .env file, in django project
In my project, I just added new security methods, separating the .env from the project into another folder and adopting the use of new processes. To do this, I followed the python-dotenv lib documentation, which I use in my app. But even following the suggestion I can not find all the parameters, since I end up having the following error: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty My settings: from dotenv import load_dotenv env_path = Path('/home/user/configs') / '.env' load_dotenv(dotenv_path=str(env_path)) How can I resolve this problem from the specific path? Note: I use in my project, python 3.4.5 and django 1.9.4, but I do not believe that the problem is caused by the old versions adopted in the project. Another important detail is that the .env file is correct, because when I use it in the same folder where I find the file settings.py it works without problems! -
Django urls.py not updated unless Apache reload
It seems that changes to the urls.py file in my Django project are ignored unless I reload Apache. Any ideas why this is happening? This is my virutal host file: <IfModule mod_ssl.c> <VirtualHost www.mydomain.com:443> ServerName www.mydomain.com ServerAdmin myaddress@mydomain.com WSGIScriptAlias / /var/www/html/www.mydomain.com/myproject/wsgi.py WSGIDaemonProcess myproject python-path=/var/www/html/www.mydomain.com:/var/www/html/www.mydomain.com/env/lib/python3.6/site-packages WSGIProcessGroup myproject <Directory /var/www/html/myproject> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # Let's Encrypt files SSLCertificateFile /etc/letsencrypt/live/www.mydomain.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/www.mydomain.com/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> </IfModule> Changes are otherwise applied instantly, as I can check via the show_urls command from django-extensions. -
preffix dont use properly with celery
I am using celery and redis as a result backend but i am having this issue: when i execute a task with add.apply_async((1,2), task_id='1') i am getting as result in redis "user:1:key" which is what i want, but when i execute again with different task id add.apply_async((1,2), task_id='2') i am getting this result in redis "celery-task-meta-2". I am using 'user' as prefix in my Django app setting. settings: # CELERY/REDIS settings BROKER_URL = 'redis://localhost:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Africa/Casablanca' CELERY_SEND_EVENTS=True CELERY_RESULT_BACKEND='redis://localhost:6379/1' # REDIS CACHE settings CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://localhost:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, "KEY_PREFIX": "user" } } -
How To genrate a 6 digita string as a primary key in django
hellow everyone i am create a e commerce website and i want to create a unique refer code for all user's so how i can add a refer code column as a primery key in django and i want to creatre a refer code as 6 digit strinf like SHIKDC so please tell me how i can create a 6 digit string column as a primary_key in django i konw how to create a 6 digit random string but i want to create a unique 6 digit random key for all user so please tell me how i add this refer code column -
Database Design for tracking user flow
I want to design a user tracking system between different models. There is a Module table which is related to sections and sections are related to sub-sections. Each sub-section can relate to different independent tables. The independent tables store different items (slides, videos, texts) which the user can go through in a linear flow just like a Coursera course. The flow will be predetermined by us but can be changed by us. So, the linear flow between the sub-sections can't be hardcoded. I also need to keep track of the user's progress through these sub-sections. For Example: A sub-section can point to game table where the user_info, game_score, game_completion_date_time will be stored or there might be case where the sub-section is pointing to slides table storing slide_text, slide_url and user_info. I want to keep track of changes in those table so what should be my approach. Below i have posted an image in which i am approaching to the problem. -
Need a software recommendation for web services
I made a project in Pycharm 2018.3 community version with django and now I wanted to create a web server to host it. Also, I downloaded Mamp to create a web server, but I don't know how to export/import my project from Pycharm to Mamp. You recommend host it with Github directly in Pycharm, or migrate the project to some software else? Thanks very much! -
Django Intersection on Mysql database
My table with this values: id, product, category 1, A, 1 2, B, 1 3, B, 2 4, C, 1 5, C, 2 6, D, 2 7, E, 2 8, E, 3 9, F, 3 10, F, 4 I need to select only products matching category (1 OR 2) AND category (3 OR 4) in Django. Expected result is only product: E I have error "intersections are not supported in mysql" How i can achieve this using Q() ? This query return no result but work. main_query = Q() main_query &= Q(category__in=[1,2]) main_query &= Q(category__in=[3,4]) models.Table.objects.filter(main_query) -
Django: Creating a function-based view Login & Signup form in one single page
I want to create a landing page similar to linkedin's where it has the signup form and the login form at the navbar. I'm currently using a single form for both the signup and login in forms.py: forms.py class UserRegisterForm(UserCreationForm): firstname = forms.CharField(max_length=200, label='') lastname = forms.CharField(max_length=200, label='') email = forms.EmailField(label='') class Meta: model = User fields = ['username', 'firstname', 'lastname', 'email', 'password1'] My template includes 2 {{ form }}s and each has a submit button. Button for the sign up {{ form }}: name='signupbtn' type='submit' Button for the login {{ form }}: name='loginbtn' type='submit' Now I have trouble trying to login or authenticate the user that I created (which is the super user). My signup/login view goes as follows: def index(request): if request.method == 'POST': if 'signupbtn' in request.POST: form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You may now login.') return redirect('index') elif 'loginbtn' in request.POST: username = request.POST['username'] password = request.POST['password1'] form = UserRegisterForm(request.POST) if form.is_valid(): user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('home') else: form = UserRegisterForm() return render(request, 'users/index.html', {'form': form}) Is it possible that I need to create 2 forms in my … -
I am trying to install "pip install mysqlclient" and it fails everytime. Tried all other things but also didnt work. What should I do?
I am trying to install "pip install mysqlclient" and it fails everytime. I also tried "pip install --only-binary :all: mysqlclien" and also not worked. Then I also downloaded whl file and also did't work. I need help -
how to create 3 dependent dropdown list using django and ajax
i am trying to build a 3 dependent dropdownlist where the user select the first dropdownlist and the system will open display just the data related to the selected option. the 3 dropdown list contains conuntries citys roads where all the data are fetched from the sqlite 3 database . until now i was abel to create a dependent dropdownlist only between the country and city without the road models.py from django.db import models class country(models.Model): name = models.CharField(max_length=100) def __str__(self): return str(self.name) class city(models.Model): name = models.CharField(max_length=100) MouhafazatID = models.ForeignKey(country,on_delete=models.CASCADE) def __str__(self): # return'id : {0} MouhafazatID :{1} Name :{2}'.format(self.id,self.MouhafazatID,self.name) return str(self.name) class road(models.Model): Vil = models.CharField(max_length=100) CazaID= models.ForeignKey(city,on_delete = models.SET_NULL, null=True) MouhafazaID= models.ForeignKey(country,on_delete = models.SET_NULL,null=True) def __str__(self): return str(self.Vil) urls.py from django.contrib import admin from django.urls import path, include from.views import * # from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', home2), path('getdetails/', getdetails), path('getdetails2/', getdetails2), home2.html <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script> <script> $(document).ready(function(){ $('select#selectcountries').change(function () { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); var country_name = optionSelected.text(); data = { 'cnt' : country_name }; ajax('/getdetails',data,function(result){ console.log(result); $("#selectcities option").remove(); for (var i = result.length - 1; i >= 0; i--) { $("#selectcities").append('<option>'+ … -
Django 2.1 + Ecommerce : How to create a select Function for selecting a Product Color/Size from the client side?
i am working on an Online Shop, and i want the customers to be able to select the product size and the color from the product page like this: so far that's what i have accomplished: but i can't select the Color nor the Size yet here's my HTML Code: ... <tr> <td class="my-prod-title">Color</td> <td> <ul id='color'> {% for color in product.color.all %} <li class="square my-2" style='background-color:{{color}};'> </li> {% endfor %} </ul> </td> </tr> <tr> <td class="my-prod-title">Size</td> <td> <ul id='size'> {% for size in product.size.all %} <li class="my-2">{{size}}</li> {% endfor %} </ul> </td> </tr> ... What do i need to make that functionality ? -
Is it possible to create a Django app which only reads data from external database and provides REST API?
In other words - I want to create a simple Django Rest Framework app which preferable doesn't need it's own database. This Django API app should only provide data for some external frontend app (e.g. Angular/Webpack stack). -
How to check for loop value in if else using jinja2
hy guys i am new in django and i creat a template like this in this template i am use jinja2 if else and according to data it is true but in this code it is not true please check this code and tell me ans hear users = [1,2,3,4,5,6,7] and user.referredby = 3 {% for i in users %} {% if "{{user.referredby}}" == "{{i}}" %} <h5>referred by : </h5><p>{{i.username}}</p> {% endif %} according this data my if condition is true but in my code this condition is not true please tell me how i check this correctly