Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to make any changes to view.py file
I'm hosting a web server with Django framework . Then , I'm using Notepad++ NppFTP to modify and upload those files . I can modify the html files and upload to ftp server instantly with Notepad++ NppFTP .But for updating view.py , I found that even though it says view.py 100% upload success , the web seems to be unchanged regarding to the new view.py file . Is that the way to modify the view.py file different to modifying HTML files ? -
How to change Wagtail's default language?
I'm using headless Wagtail and want to change the default backend language to Portuguese (pt-pt). Following wagtail's docs: # settings.py USE_I18N = True LANGUAGE_CODE = "pt-pt" Then why I try to publish a wagtail page I get the following error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/pages/11/edit/ Django Version: 3.1.2 Python Version: 3.9.0 Installed Applications: ['home', 'search', 'news', 'about_us', 'product', 'dashboard', 'wagtail_headless_preview', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'wagtail.api.v2', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders'] Installed Middleware: ['django.middleware.locale.LocaleMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware'] Traceback (most recent call last): File "C:\Users\diogo\OneDrive - Universidade de Tras-os-Montes e Alto Douro\Marfon\venv\lib\site-packages\django\core\handlers\exception.py", line 52, in inner response = get_response(request) File "C:\Users\diogo\OneDrive - Universidade de Tras-os-Montes e Alto Douro\Marfon\venv\lib\site-packages\django\core\handlers\base.py", line 195, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\diogo\OneDrive - Universidade de Tras-os-Montes e Alto Douro\Marfon\venv\lib\site-packages\django\views\decorators\cache.py", line 49, in wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\diogo\OneDrive - Universidade de Tras-os-Montes e Alto Douro\Marfon\venv\lib\site-packages\wagtail-2.11rc1-py3.9.egg\wagtail\admin\urls_init.py", line 170, in wrapper return view_func(request, *args, **kwargs) File "C:\Users\diogo\OneDrive - Universidade de Tras-os-Montes e Alto Douro\Marfon\venv\lib\site-packages\wagtail-2.11rc1-py3.9.egg\wagtail\admin\auth.py", line 179, in decorated_view response = view_func(request, *args, **kwargs) File "C:\Users\diogo\OneDrive - Universidade de Tras-os-Montes e Alto Douro\Marfon\venv\lib\site-packages\django\views\generic\base.py", line 85, in … -
Retrieving object by email from object manager class
I am using Django 3.10 I am extending the User model, to create a custom user model. I want the unique attribute on the User object to be the email. When creating the object, if an object with the same email exist, an Integrity error will be raised and trapped, and the existing object is returned instead. I am not sure the best way to implement this functionality. This is my code so far: from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class FooUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password=None, username=None, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) if username: extra_fields['username'] = username user = self.model(email=email, **extra_fields) user.set_password(password) try: user.save() except IntegrityError as e: if not 'creating_superuser' in extra_fields user = FooUserManager.get(email=email) # <- obviously won't work ... else: raise e return user def create_superuser(self, email, password, username, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) extra_fields['creating_superuser'] = True if extra_fields.get('is_staff') is … -
I want to find experienced Django developers to work in their projects
I would like to find Django developers who want help on their projects and I can learn by helping them and also get some advice about my job. -
Data don't appear in html page in Django
i have problem with my data , it's don't appear in my html page i tried do this but nothing happen model.py : class BestArticals(models.Model): name = models.CharField(max_length=240) url = models.URLField(default="",max_length=240) image = models.ImageField(upload_to='images/',null=True, blank=True) def get_image(self): if self.image and hasattr(self.image, 'url'): return self.image.url else: return '/path/to/default/image' def __str__(self): return self.name veiws.py : def Best_Articals(request): best_posts = BestArticals.objects.all() context = {'best_posts' : best_posts} return render(request,'android/side_bar_good_posts.html',context=context) html page : {% for post in best_posts %} <ul style="text-align:right"> <li> <img src="{{post.get_image}}" height="80px" width="80px"> <a href="{{post.url}}" style="color:black"> {{post.name}} </a> </li><br> </ul> {% endfor %} what is the problem here -
How to create an object whose name is passed as a parameter
I want to create an object before i save an object related to it, how can i do that? In my Item model i have tags ManyToManyField. I want to create or update Item passing a Tag name as a parameter even if Tag object with this name is not created yet. models.py class Tag(models.Model): name = models.CharField(primary_key=True, max_length=50, unique=True, db_index=True) items_num = models.BigIntegerField('Number of Items', default=0) class Item(models.Model): category = models.ForeignKey('Category', on_delete=models.DO_NOTHING) tags = models.ManyToManyField('Tag') user = models.ForeignKey('users.User', on_delete=models.CASCADE) name = models.CharField(max_length=30) description = models.CharField(max_length=300, blank=True) main_image = models.ImageField(default='main_image_test_path') CHEAP = 'CH' MIDDLE = 'MI' EXPENSIVE = 'EX' VERY_EXPENSIVE = 'VE' MOST_EXPENSIVE = 'ME' PRICE_CHOICES = [ (CHEAP, 'Cheap'), (MIDDLE, 'Middle'), (EXPENSIVE, 'Expensive'), (VERY_EXPENSIVE, 'Very Expensive'), (MOST_EXPENSIVE, 'Most Expensive') ] price = models.CharField( max_length=2, choices=PRICE_CHOICES, default=CHEAP ) status = models.BooleanField(default=1) # 1 - Active, 0 - Inactive serializers.py class ItemListSerializer(serializers.ModelSerializer): tags = serializers.PrimaryKeyRelatedField(many=True, queryset=Tag.objects.all()) category = serializers.SlugRelatedField(slug_field='name', queryset=Category.objects.all(),) user = UserSerializer(read_only=True,) class Meta: model = Item fields = ('id', 'name', 'category', 'tags', 'user', 'price', 'status',) def validate_tags(self, value): print(value) if len(list(set(value))) != len(value): raise serializers.ValidationError('All tags must be unique') return value def create(self, validated_data): validated_data['user'] = self.context['request'].user for tag in validated_data['tags']: tag.items_num += 1 tag.save() validated_data['category'].items_num += 1 validated_data['category'].save() … -
How come I can set these fields with Postman even though my perform_create method is setting these fields at save with the requested user?
Here is my serializer class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' My model for items class Item(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) title = models.CharField(max_length=200) #need to add images description = models.TextField() price = models.CharField(max_length=50) created_on = models.DateTimeField(auto_now_add=True) Here is the viewset class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer permission_classes = [IsOwnerOrReadOnly] def perform_create(self, serializer): serializer.save(user=self.request.user) brand_qs = Brand.objects.filter(owner=self.request.user) if brand_qs.exists: serializer.save(brand=brand_qs[0]) So, when using postman I am still required to enter the user and brand fields, and can make the user field any user I want, doesn't save with the requested user. -
Pagination or limit range happybase
Need make to filter in happybase django or a pagination. similar in sql SELECT * FROM tabla LIMIT 1,10 -
Django limiting Foreign Key values based on model field choice
Currently I have two tables, user types and user subtypes, that needs to be related based on condition. For example.: The UserType USER_A can only be related to UserSubtypes TYPE_A and TYPE_B entries The UserType USER_B can only be related to UserSubtypes TYPE_C entries The UserType USER_C can only be related to UserSubtypes TYPE_D entries class UserTypes(models.Model): USER_TYPES = [ ("USER_A", "USER_A"), ('USER_B', 'USER_B'), ('USER_C', 'USER_C'), ] account_type = models.ForeignKey(UserSubtypes) user_type_name = models.CharField(choices=USER_TYPES, default="USER_A") class UserSubtypes(models.Model): USER_SUBTYPES = [ ("TYPE_A", "TYPE_A"), ('TYPE_B', 'TYPE_B'), ('TYPE_C', 'TYPE_C'), ('TYPE_D', 'TYPE_D'), ] user_type_name = models.CharField(choices=USER_TYPES) How can I achieve this kind of conditional relationship? -
With python, getting and passing values in json data
there is a "data" coming in json. I show it with "columnar", but because there are more than one row, it creates a new table. What I really want to do is show it all in one painting. How can we achieve this? data = "{'symbol': 'APPLE', 'positionAmt': '-0.001', 'entryPrice': '268.83000'} {'symbol': 'BLACKBERRY', 'positionAmt': '-0.001', 'entryPrice': '390.12000'}" headers = ["Symbol", "positionAmt", "Entry", "Side"] for sym in data: if sym['positionAmt'][:1] == "-": result = [ [sym['symbol']], ] table = columnar(result, headers=headers) print(table) Whenever a new line comes up, the table header "symbol" increases. -
I want to add a search functionality to each and every word in my home page and display it in another html template in django app
For Eg. My home page contains a register button, a contact us button, an About us button, and a few more like this. So if someone types about us in the search tab then the search functionality should point it towards the about us button. Please share your answers if this is possible in Django. -
Unable to Retrieve Multiple image in Django Post detail Page after succesfull upload in admin page
I have a BLOG/NEWS website with the following Model.py, Views.py and and a post_detail.html page which i can successfully upload an image or file in the admin page panel when creating a post but cannot retrieve the image in my post_detail.html page. I mean am unable to Retrieve Multiple image on my blog Post when i do the following code and after a succesful upload of images on the admin panel . I need help in solving this problem amicably. And i have my admin.py configured accurately which make provision for uploading multiple images on a specific post in django Models.py class Post(models.Model): image = models.ImageField(upload_to="images/") title = models.CharField(max_length=150) summary = models.CharField(max_length=250) class PostImage(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) images = models.ImageField(blank=True, upload_to='images') @property def image_url(self): return self.get_absolute_url() def get_absolute_url(self): return self.image.url Views.py class PostDetailView(DetailView): model = Post def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['related_posts'] = Post.objects.filter(category=self.object.category).order_by('?')[:2] Context['multiple_image']= PostImage.objects.all() return context post_detail.html <div class="w-full md:flex md:-mx-2 "> {% for image in mutiple_images %} <div class="w-full md:w-1/2 px-2"> <a href="{{ postimage.get_absolute_url }}"> <img class="object-cover w-full h-24 m-2 rounded-lg" src="{{ postimage.images.url }}" alt=""> </a> </div> {% endfor %} </div> Unfortuanately the image refuse to appear in the detail page and i strongly believe … -
Django ORM -- Why is blank=True/null=False failing with default="" (and blank=False/null=True with default=None as well)
I have the following model: class MyModel(models.Model): # normal fields calculated_field = models.CharField(max_length=4, blank=True, null=False, default="") def save(self, *args, **kwargs): self.calculated_field = self.function_to_calculate_field_value() super(MyModel, self).save(*args, **kwargs) This is calculated based on values from another model where MyModel has a ManyToMany relationship. This works with my forms and does what I want. When I bulk upload data via a JSON command, though, I get a NOTNULL constraint failed error despite the default value being an empty string. I've tried switching it up like so: calculated_field = models.CharField(max_length=4, blank=False, null=True, default=None) But this gives me this error in the console: {'calculated_field': ['This field cannot be blank.'] I know I'm not supposed to set a CharField to null=True and blank=True, but I'm seriously running out of ideas here. Why are neither of these options working? -
Remove shopping cart django
how can I delete a user's shopping cart automatically after a certain time (for example, after a one day)? my view: def remove_cart(request, id): url = request.META.get('HTTP_REFERER') Cart.objects.get(id=id).delete() return redirect(url) my models : class Cart(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) variant = models.ForeignKey(Variants, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() create = models.DateTimeField(auto_now_add=True) -
mysql 5.7 breaking tests ( mysql connection gone )
I am facing a test failures while updating a code from mysql5.6 to 5.7. Only one test which is using multiprocessing.Process is failing. MySQLdb._exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query') The above exception was the direct cause of the following exception Is there any change in related with threading in mysql5.7 or i am missing some thing ? -
How to add tasks to a different tiles with ONE tile - Many Tasks relation?
I am trying to relate a tile for several tasks to django, but simply the relationship continues to give error when I try to add a second task to the same tile. I leave the code of the different models below and the respective error: class Tile(models.Model): STATUS = Choices('Live', 'Pending', 'Archived') launch_date = models.DateTimeField(editable=False, auto_now_add=True) status = models.CharField(choices=STATUS, default=STATUS.Live, max_length=25) def __str__(self): return "Tile date -> " + str(self.launch_date) + " with status -> " + self.status class Task(models.Model): TYPES = Choices('Survey', 'Discussion', 'Diary') tile = models.ForeignKey(Tile, on_delete=models.CASCADE) title = models.CharField(max_length=100) order = models.IntegerField() description = models.CharField(max_length=500) task_type = models.CharField(choices=TYPES, default=TYPES.Survey, max_length=25) def __str__(self): return str(self.tile) + " " + self.title I try to add a second task to the same tile and: In the end you are supposed to be able to add several different tasks to the same tile in the following way: Please, what is the problem right here? -
Database for django deployed application
I have a Django website where you can fill a form and after that you can upload/download files. I'm using PostgreSQL database and everything works well locally. If I deploy the site on the server (using cloud foundry) and I want to upload a file, I receive this error: relation "Upload_Page_form_data" does not exist I understand that the db it's not created on the server but my question is how this process it's working? After creating the model in Django, my db is automatically generated. But when i want to deploy the application, I have to manually create the tables, rows and colls for being available on the server? If yes, how? -
Django {% extend static "template.html" %} throwing TemplateSyntaxError
I have a template.html file full of some boiler plate html text. Then in index.html I have: {% load static %} {% extends static 'template.html' %} In settings.py I have (relevent things): INSTALLED_APPS = [ 'notes.apps.NotesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' However, when I try to render index.html I get a TemplateSyntaxError at 'extends' takes one argument. When template.html was placed in the same directory as index.html and I used {% extends 'template.html' %} everything worked fine. -
Dot notation request handling in Django Rest Framework
I have a serializer class (Not ModelSerializer) that needs to take a list of dot notation configuration from the request: class ConfigurationSerializer(serializers.Serializer): a_value= serializers.CharField( required=False, source='a.value', ) I thought by specifying the source attribute, the serializer will know a.value in the request.data will represent a_value in the ConfigurationSerializer. But when I run the serializer.is_value(), I don't see any data inside serializer.data: def post(self, request): serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): print(serializer.data) #-----> this is empty Is it the correct way to do it? How can I translate the dot notation from the request object to serializer? -
Page not found: No CustomUser matches the given query
Summary of project: (Sorry if this post is too long). You post a funny comment and people can read your post and then click a button to like you. If you liked their post and they liked yours then you can both chat. Summary of problem: Any time I click the "like" button on a post I get the following error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/vote/ Raised by: users.views.ProfileDetailView - No CustomUser matches the given query. So basically I cannot get the "like" button to save the current user + the post author to the "liked" table. I've spent like two weeks reading the Django docs and trying different things in the view but now I'm just lost... I think it's my URL... Setting.py AUTH_USER_MODEL = 'users.CustomUser' Users/models.py class CustomUser(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField( get_user_model(), on_delete=models.CASCADE, primary_key=True, ) first_name = models.CharField(max_length=100, blank=True) def __str__(self): return f'{self.user.username}' Userpost/models.py class Posts(models.Model): date_posted = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) caption = models.CharField(max_length=160, blank=True) def __str__(self): return self.caption Voting/Models.py class Like(models.Model): liker = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name='liker', ) likee = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name='likee', ) date_created = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): super(Like, self).save(*args, **kwargs) … -
Dango & Vue.Js project
I've been building a lot of test websites in Django, and took an online course in Django + Vue.JS, but I'm not 100% comfortable yet (with Vue.js and bigger projects). So I have a question. First a small description about my idea; I want a basic home page, just some information about my service, with some additional pagel about, learn, products, etc. You get it. Then there has to be a user register/login section. I've created one before with an email verification, but I also want to add a monthly payment (any tips/tutorials are welcome). After you've registered and logged in, you have to be redirected to the Web-App I want to build. In the web-app I want to build a few different apps, let's say; I want to build a stock analyse app. Where every analysing tool has other calculations, etc. The question I have; How does the architecture of the app should look like? Should I have a home-app, user-app, stock-app? Where only the stock-app has to be combined with Vue.js, how to make this happen? And how to make sure only logged in users can access the web-app? Or is this possible with @login_required? Hope someone can … -
Admin folder inside template folder
So I have created a template folder inside my project (project/template). Inside the template folder I've created a subfolder called admin (project/template/admin). Now the issue is that whenever I try to access the Django admin page, it redirect me to the page inside the subfolder(project/template/admin/index.html) Is there a way around this? -
AttributeError: 'NoneType' object has no attribute 'startswith' while launching the Django App
while running the command >python manage.py runserver to launch the app getting the below error, is there any package needs to be updated?? File "D:\venv\lib\site-packages\django\db\backends\mysql\base.py", line 201, in get_connection_params if settings_dict['HOST'].startswith('/'): AttributeError: 'NoneType' object has no attribute 'startswith' -
Implementing pdb debugger in django ace editor
How could I implement pdb debugger in django ace editor so that the user can debug the code and see the debug output in browser console. If anyone can suggest or guide something then that will be great help. -
"detail": "Authentication credentials were not provided." in every api call in django
Iam developing authentication using token in django rest. I successfully developed the login api view where, the token is generated and returned after user is logged in using the credentials. But now my other simple get apis of blog posts and also sign up api is asking for token, when I call that api. For eg: when i call http://127.0.0.1:8000/api/blog-post , it is giving "Authentication credentials were not provided." I dont want this. I dont need users to log in to simply view the blog posts on my web. How to solve this?? This is my login view class LoginUserView(GenericAPIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) serializer.is_valid(raise_exception=True) user = serializer.validated_data["user"] token, created = Token.objects.get_or_create(user=user) return response.Response({"token": token.key}, status=status.HTTP_200_OK) This is my login user serializers class UserLoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(label='Email Address') class Meta: model = User fields = [ 'email', 'password', ] extra_kwargs = {"password": {"write_only": True}} def validate(self, data): # user = None email = data.get("email", None) password = data.get("password") if not email: raise serializers.ValidationError("Email is required for login") if not password: raise serializers.ValidationError("Password is required for login") user = authenticate(email=email, password=password) if not user: raise serializers.ValidationError("This email is …