Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to configure urls for the main app in Django?
This is the project: myProject/ app1/ -urls.py -views.py myProject/ -urls.py -views.py website/ -urls.py -views.py Where do I configure the urls for the website? In myProject/urls.py or website/urls.py? Here is myProject/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), ] So I'm not using website/urls.py... Can I remove website/ app an use myProject/ as the main app? Thanks -
upgrade django admin panel white spaces [closed]
I recently upgraded my Django version from 2.2.14 to 3.2.13 LTS, everything seems to work fine but now I have a display bug in the admin panel where there is a big white space with all the text at the bottom instead of on top. I have to scroll down in order to see the fields. -
Add all the templates to urls.py url_patterns in django
I have a lot of templates in my project. I want to add them to urls.py without typing each one of them. I want to loop them in my url_patterns. Is there any way I can add all my templates in the urls.py? -
How to represent JSONField out as comma-seperated string in Django Admin list page?
Consider I have a Django model with a custom JSONField as below, # models.py class JSONCustomField(models.JSONField): ... class JSONFieldModel(models.Model): json_field = JSONCustomField(default=list) This model is connected via Django Admin # admin.py @admin.register(JSONFieldModel) class JSONFieldModelAdmin(admin.ModelAdmin): def expected_json(self: JSONFieldModel): return self.json_field list_display = ("id", "json_field", expected_json) This setup resulting an output like the below, How can I tell Django to parse and display my "list of strings" to "comma separated strings"? Notes Django version 3.2.X Assume that the json_field will only accept list inputs (Just like an ArrayField) -
How to map a request body in node js
I have this data that format like this router.post("/add", jsonParse, (req, res) => { console.log(req.body.data) //[{"id":"someid","order":1,"configuration":"Config"}]// }) I want to get the value of id the someid I tried using var deviceData = req.body.data.map(function (d) { return d.id; }); but is says that req.body.data.map is not a function -
why this command gives error pip install waitress
Fatal error in launcher: Unable to create process using '"E:\FinalDjango\miniblog\myenv\Scripts\python.exe" "E:\FinalDjango - Copy\miniblog\myenv\Scripts\pip.exe" install waitress': The system cannot find the file specified. -
can not add or update child row, foreign key constraint failed
subscriber_package_forms = subscriber.package.form # subscriber packages forms. a = subscriber_package_forms.replace('[', '') b = a.replace(']', '') c = b.replace("'", '') d = c.replace('''"''', '') e = d.replace("'", '') f = e.split(',') #search active columns of all the packages from main database. for frm in f: frm = int(frm) try: form_columns_object = form_columns.objects.using(main_db).filter(form_id = frm).first() except: pass if form_columns_object == None: pass else: form_columns_dict = model_to_dict(form_columns_object) form_instance = FormModel.objects.using(main_db).get(id = int(form_columns_dict['form'])) user_instance = User.objects.using(main_db).first() #get(username = form_columns_dict['user']) # id = form_columns_dict['id'] form_columns.objects.using(db_name).create(columns = str(form_columns_dict['columns']), form = form_instance, user=user_instance) This code is working fine in my local setup. But i am facing a problem after committing it on server. We have error in last line of the code i guess -
Django Filtering to Get Popular Posts
I have two different models. HitCount model stores IP addresses whose was viewed Post. And what i want is filtering popular 3 posts which viewed more. I've tried some queries but i couldn't. I am sharing my models with you. class Post(ModelMeta, models.Model): title = models.CharField(max_length=255, verbose_name='Başlık', unique=True) slug = models.SlugField(max_length=255, unique=True) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='blog_posts', verbose_name="Yazarı") category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='blog_posts', verbose_name="Kategorisi", null=True) tags = models.ManyToManyField(Tag, related_name='blog_posts', verbose_name='Etiketler') image = models.ImageField(verbose_name='Fotoğraf (800x460)') content = RichTextField() description = models.TextField(null=True) status = models.IntegerField(choices=STATUS, default=0, verbose_name='Yayın Durumu') created_at = models.DateTimeField(auto_now_add=True, verbose_name='Oluşturulma Tarihi') updated_at = models.DateTimeField(auto_now=True, verbose_name='Güncellenme Tarihi') @property def get_hit_count(self): return HitCount.objects.filter(post=self).count() class HitCount(models.Model): ip_address = models.GenericIPAddressField() post = models.ForeignKey("Post", on_delete=models.CASCADE) def __str__(self): return f'{self.ip_address} => {self.post.title}' -
return render is not working in another python file - Djanjo
I'm working on registration page and for basic validation like if user already registered, password is complex or not etc .. for that I've created a separate file and and if all checks completed I am trying to redirect but from the secondary python file redirect and even render is not working it just simply return me the same registration page but when I use redirect on the same views.py file redirect is working. That is a weird behavior? Or I am doing something wrong? [views.py] from django.shortcuts import redirect, render from .utils.registration import Register # Create your views here. def register(request): if request.method == "POST": name = request.POST['name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] # return redirect("/verification/") Register(request=request, name=name, username=username, email=email, password=password) [registration.py] from django.contrib import messages from django.contrib.auth.models import User from django.shortcuts import redirect, render class Register: def __init__(self, request, name, username, email, password) : self.request = request self.name = name self.username = username self.email = email self.password = password self.error_message = None self.is_email = User.objects.filter(email=self.email) self.is_username = User.objects.filter(username=self.username) self.is_user() def is_user(self): if self.is_email and self.is_username: print(1, "######################################################") self.error_message = "Hmm.. Seems like your email and username already registered with us." self.show_error() elif self.is_email: print(2, … -
django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution on highload
I have the django project which works with PostGresql db, both in docker containers. It works Ok, but on highload sometimes gives the django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution error. Is there a way to tune the django db connector for more retries or more timeout to solve these case? -
Python Django imported settings are not visible to other imported files
i have an old project with Python 2.7 and Django 1.6. I am trying to get run under windows. I have the files structure like: myproj/ |-- myproj/ | |-- init.py | |-- manage.py | |-- settings.py | |-- settings_common.py | |-- settings_development.py | |-- settings_production.py | |-- urls.py My settings.py: """Code to import development/production settings.""" from platform import node try: from settings_common import * except ImportError: pass PRODUCTION_HOSTS = ['mydbproj'] try: from settings_definehost import PRODUCTION_HOSTS except ImportError: pass if node().split('.')[0] in PRODUCTION_HOSTS: from settings_production import * else: from settings_development import * try: from settings_local import * except ImportError: pass and settings_common.py is: """Common settings for the mabdb.""" import os from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP TEMPLATE_CONTEXT_PROCESSORS = TCP + ( 'django.core.context_processors.request', ) ROOT_URLCONF = 'urls' SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) ... ... ... and settings_development.py is: """Setting for development systems.""" DEBUG = True # TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = SITE_ROOT .. So when i call python manage.py runserver, i get this error … -
Connecting users in Django
I want a main user who can register multiple sub-users and can see the registered users. Please guide me to write sub users model and connect them to main user. -
How to remove a once-off value for a field from django models
I would like to know how can I remove this default value I set. While migrating, I was prompted to give a once off value for a field which could not be null, I assigned the value of 0 to it. Now I get this error: I have commented out that specific field, and what confuses me as well is that it's an image field not an autofield, though I do have a faint memory of having an autofield. I double check the other app's models for this field, but I haven't found another. I also deleted the tables from the database and migration files multiple times since I got this error, but I'm still sitting with this problem. -
Django: Update one data from Database
I have two html files for attendance_in and out, just a simple forms. If I want to punch in, the data was created (begin_time). I'm having a hard time updating the end_time. This is my code. models.py class Attendance(models.Model): begin_time = models.TimeField(verbose_name="in") end_time = models.TimeField(verbose_name="out") views.py def attendance_in(request): if request.method == 'GET': return render(request, 'attendance_in.html') if request.method =='POST': begin_time = request.POST.get('begin_time') Attendance.objects.create(begin_time=begin_time,) return redirect('/user/attendance/out') def attendance_out(request): if request.method == 'GET': return render(request, 'attendance_out.html') if request.method =='POST': ....... urls.py urlpatterns = [ path('attendance/in/', views.attendance_in), path('attendance/out/', views.attendance_out), ] The attendance_in was working. But I am not sure how to update the end_time. -
Why do I get this error ? ValueError: Cannot assign "'14'": "Jobs.category" must be a "Category" instance
I'm tring to add jobs to the database through a form. However I get the error " ValueError: Cannot assign "'14'": "Jobs.category" must be a "Category" instance." When I submit. I'm not sure How I can solve it. Category is a foreign key in the Jobs model. The user should be able to chose from categories already existing in the database. This displays in the form however on submitting. The error above is thrown. I'm way in over my head here. I appreciate any guidance. forms.py class JobForm(forms.ModelForm): CATEGORY_CHOICES = [] categories = Category.objects.all() for category in categories: CATEGORY_CHOICES.append((category.id, capwords(category.title))) title = forms.CharField( required = True, widget = forms.TextInput(attrs = {'class': 'form-control ', 'placeholder': 'e.g Software Engineer'}), ) category = forms.ChoiceField( choices = CATEGORY_CHOICES, required = True, widget = forms.Select(attrs = {'class': 'selectpicker border rounded', 'placeholder': 'select category'}), ) class Meta: model = Jobs fields = [ "title", "category", ] models.py class Category(models.Model): title = models.CharField(max_length= 200, null = True, blank = True) description = models.TextField(null = True, blank = True) uniqueId = models.CharField(null = True, blank = True, max_length = 100) categoryImage = models.ImageField(default = 'category.png', upload_to = 'upload_images') slug = models.SlugField(max_length = 500, unique=True, blank = True, null … -
What is the best practice for handling form errors in Django?
I am new to Django and I am wondering how you are supposed to handle errors in your forms. In my case I generate my form from my database in order to stick as much as possible to the DRY principle. Here is a (very) simple example : # models.py class User(models.Model): firstname = models.CharField(max_length=50, validators=[ RegexValidator('^[A-Za-z]*$'), MinLengthValidator(2)]) # forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ['firstname'] error_messages = { 'firstname': { 'required': 'Please enter your firstname', 'min_length': 'Your firstname must contain at least 2 characters', 'max_length': 'Your firstname must not exceed 50 characters', 'invalid': 'Your firstname must contain only letters' } } Is it a good way of validating data ? Or should I handle form errors in another file with conditions instead of ORM validators ? What is the best practice ? Thanks in advance ! -
Get post request from django python using Node JS
Using Node JS, I want to get the data that I posted. in my views. py if request.method == 'POST': post_data = json.loads(request.POST.get("data")) response = requests.post('http://localhost:3000/path/', data={ 'data': request.POST.get("data")}) in my node js const bodyParser = require("body-parser") const jsonParse = bodyParser.json() router.post("/path", jsonParse, (req, res) => { //I have some function here, but I needed to use the data from my django views. console.log(req.body) //the console is {}, I want to get the data that I posted using the django views//}) Maybe my approach is wrong. I am new to node JS that's why I'm asking for help. I'm open to any suggestion. The django views are working. I just don't know how to receive that in Node JS way -
How django LoginRequiredMixin use templates. How can we pass context_data to the login form template
How django LoginRequiredMixin takes templates. I cound not find anything how it is taking the templates. I had added account folder inside templates and then LoginRequiredMixin is taking my template but how it is wokring and how can i pass a context data to the template of login form -
Sign In with Apple, decoded Apple response
I've implemented 'Sign In with Apple' from this source (https://gist.github.com/aamishbaloch/2f0e5d94055e1c29c0585d2f79a8634e?permalink_comment_id=3328115) taking into account the comments of NipunShaji and aj3sh. But it doesn't works because Apple sends incomplete data: I recieve decoded = {'iss': 'https://appleid.apple.com', 'aud': '...', 'exp': 1664463442, 'iat': 1664377042, 'sub': '.....', 'at_hash': '....', 'auth_time': 1664377030, 'nonce_supported': True} without email data). According to the Apple's documentation typical response contains email: https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_rest_api/authenticating_users_with_sign_in_with_apple. What I've missed? -
Best architecture for dynamically validating and saving field
I am looking for the good architecture for my problem. I am using django rest framework for building an API. I receive a list of dict which contains an id and a list of values. The list of values need to be validated according to the id. Example of my code: class AttributesSerializer(serializers.Serializer): id = serializers.PrimaryKeyRelatedField(queryset=Attribute.objects.all(), source="attribute", required=True) values = serializers.ListField() def validate(self, validated_data): attribute = validated_data["attribute"] values = validated_data["values"] # This function returns the corresponding field according to attribute values_child_field = get_values_field(attribute) self.fields["values"].child = values_child_fields new_values = self.fields["values"].run_child_validation(values) set_value(validated_data, "values", new_values) return validated_data class SerializerExample(serializers.Serializer): attributes = AttributesSerializer(many=True) I want to parse json like this: { "attributes": [ {"id": 124, "values": ["value"]}, {"id": 321, "values": [42]}, { "id": 18, "values": [ { "location": {"type": "Point", "geometry": {...}}, "address": "an address", } ], }, ] } Currently, this code does not work. DRF seems to not try to validate all values entries for each iteration. I do not understand why... I guess I could make it work without using this fields["values"] for making the validation and just retrieve the field and use it directly, but i need this field for making the save later. do you think my architecture is … -
Call celery tasks from different server
I have a django app + redis on one server and celery on another server. I want to call celery task from django app. My task.py on Celery Server: from celery import Celery app = Celery('tasks') app.conf.broker_url = 'redis://localhost:6379/0' @app.task(bind=True) def test(): print('Testing') Calling the celery task from Django Server: from celery import Celery celery = Celery() celery.conf.broker_url = 'redis://localhost:6379/0' celery.send_task('tasks.test') I am running the celery worker using this command: celery -A tasks worker --loglevel=INFO When i call the celery task from django, it pings the celery server but i get the following error: Received unregistered task of type 'tasks.test'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? How to fix this or is there any way to call the task? -
Access model field from other model
I have three models i need to access model 1 field from model 3 class Event(models.Model): custom_title = models.CharField(max_length=255, blank=True, default='') class SubEvent(models.Model): event = models.ForeignKey( 'Event', related_name='events', on_delete=models.CASCADE ) class Notice(models.Model) event = models.ForeignKey('Event', related_name='notices', on_delete=models.CASCADE) I need to access SubEvent model data from Notice model is that possible? -
Django test client get's unauthenticated between classes
I try to build a generic test case for our django project but the client that is logged in during setUp apparently get's logged out when actually using the class in a test. class DefaultTestCase(TestCase): @classmethod def setUpTestData(self): from user.models import User self.user, _ = User.objects.get_or_create( email='demo@test.org' ) self.pw = get_random_string(16) self.user.set_password(self.pw) self.user.save() self.client = Client().login(email=self.user.email, password=self.pw) print(self.client.get('/api/me/').content) class TestMe(DefaultTestCase): def test_setup(self): print(self.client.get('/api/me/').content) The first print actually returns the correct result, but the second print (test_setup) returns b'{"message":"Authentication credentials were not provided.","status":401,"error":true}'. Why is that? I checked that the user and the password is the same in TestMe and it is but the client seems to change in between. -
is there a way to remove repeated tags?
The same tags are being repeated and displayed in the dropdown list. It is looping over the tags used in each post but it is not checking if the tags are repated or not. So is there any way that I can avoid this repetition? my dropdown list is as below: <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Tags </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for post in posts %} {% for tag in post.tags.all %} <a class="dropdown-item" href="{% url 'post_tag' tag.slug %}"> {{ tag.name }} </a> {% endfor %} {% endfor %} </div> </div> views.py def home(request, tag_slug=None): posts = Post.objects.all() #tag post tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) posts = posts.filter(tags__in=[tag]) return render(request, 'blog/home.html', {'posts':posts}) models. py from taggit.managers import TaggableManager class Post(models.Model): title = models.CharField(max_length=100) content = RichTextUploadingField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default= 'blog_default.jpg', upload_to='blog-pics') tags = TaggableManager() def __str__(self): return self.title urls has path('tag/<slug:tag_slug>/',views.home, name='post_tag'), I am using Django-taggit. Help this guy out please. -
Macbook hang and start. Couldn't open http://127.0.0.1:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
I am a beginner on Django and Python. I am starting Django project by using coding in Visual Studio Code. It was going well until my Macbook Air hang and auto restart. All of sudden my http://127.0.0.1:8000/ backend could'nt open and shows error 404, Couldn't open http://127.0.0.1:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: enter image description here Can anyone able to give me a guidance with this? I have done python manage.py runserver in Visual Studio Code and it shows: System check identified no issues (0 silenced). September 29, 2022 - 08:00:11 Django version 4.1.1, using settings 'qrmenu_backend.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. However I am not able to open it. My code was running well until my Macbook restart so I am quite sure not the code problem. Also I have access into virtual environment as well. Is that I missed any command in terminal? from django.urls import path, include from core import views urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.authtoken')), path('api/places/', views.PlaceList.as_view()), path('api/places/<pk>', views.PlaceDetail.as_view()), path('api/categories/', views.CategoryList.as_view()), path('api/categories/<pk>', views.CategoryDetail.as_view()), path('api/menu_items/', views.MenuItemList.as_view()), path('api/menu_items/<pk>', views.MenuItemDetail.as_view()), ]