Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i use a variable as django model
I want to use this function to get a list out of the database: def get_db_list(IN_DICT, **kwargs): off = kwargs.get('off', None) limit = kwargs.get('limit', None) Keyword = {} Keyword[IN_DICT['ITEM']] = IN_DICT['TYPE'] if off == None and limit == None: LIST = IN_DICT['TABLE'].objects.filter(**Keyword) else: LIST = IN_DICT['TABLE'].objects.filter(**Keyword)[off:limit] return LIST Now my problem is, that IN_DICT['TABLE'] gets passed as String: >>> type(Host_Table) <class 'django.db.models.base.ModelBase'> >>> IN_DICT['TABLE'] 'Host_Table' >>> type(IN_DICT['TABLE']) <class 'str'> How would I have to change the type? This example pulls the correct querry, but only from that table: def get_db_list(IN_DICT, **kwargs): off = kwargs.get('off', None) limit = kwargs.get('limit', None) Keyword = {} Keyword[IN_DICT['ITEM']] = IN_DICT['TYPE'] if off == None and limit == None: LIST = Host_Table.objects.filter(**Keyword) else: LIST = Host_Table.objects.filter(**Keyword)[off:limit] return LIST -
i am facing issue while retriving the check box value in python django
Views.py: def export_selectd_data_to_excel(request): if request.method == 'POST': chk_values = request.POST.getlist('chkselect',None)enter code here print(chk_values) return redirect(user_details)enter code here HTML -
Increasing the view by 1 each time some url hits?
Here I want to increase the number of views by 1 each time the detail view is called.How can I do it ? class Package(models.Model): name = models.CharField(max_length=255,unique=True) slug = AutoSlugField(populate_from='name') package_desc = models.TextField() views = models.IntegerField(default=0) views.py class DetailPackage(generics.RetrieveAPIView): serializer_class = PackageDetailSerializer lookup_field = 'slug' queryset = Package.objects.all() urls.py path('<slug>/detail/', DetailPackage.as_view(), name='detail_package'), I am very new to django rest framework.So am I going the right way by using the generics API view for such cases ? -
if user.is_authenticated not getting logged in user django
Entirely new to python and django framework. Trying to build a login/registration system.' After registering, redirects to home but user is not authenticated (returns false always) views.py def register(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') fullname = form.cleaned_data.get('fullname') password = form.cleaned_data.get('password1') user = authenticate(username=username, fullname=fullname, password=password) messages.success(request, f'Welcome to blaza {fullname}') if user is not None: login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'accounts/signup.html', {'form': form}) home.html {% extends 'base.html' %} {% block title %} Home {% endblock %} {% block content %} {% if user.is_authenticated %} Welcome, {{user.username}}! <a href="">Logout</a> {% else %} <P>You are not logged in</P> <p><a href="">Login here</a></p> {% endif %} {% endblock %} It returns false always. "You are not logged". I have tried {% if request.user.is_authenticated %} still not working. -
Add foreign key field and choices charfield to Django user creation form
I would like to modify Django UserCreationForm so that it would support creating my custom user. There are required fields company and role which both should offer some kind of selection to pick the correct choice (there will be only 3 roles but there can be hundreds of companies). I have followed several different examples but so far in vain. Below is the model. How can I command Django to add the extra fields to the user creation form? ROLE_CHOICES = [ ('role1', 'Role 1'), ('role1', 'Role 2'), ('janitor', 'Janitor'), ] class Company(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100) class Meta: ordering = ('created',) db_table = "company" def __str__(self): return self.name class CustomUser(AbstractUser): created = models.DateTimeField(auto_now_add=True) username = models.CharField(max_length=100, unique=True) email = models.EmailField(max_length=200, unique=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='%(class)s_company') role = models.CharField( max_length=100, choices=ROLE_CHOICES, default='janitor', ) phone_number = models.CharField(null=True, blank=True, max_length=20) class Meta: ordering = ('created',) db_table = "custom_user" def __str__(self): return self.username -
Sequences didn't restore from backup file
I have a Postgres DB working alongside Django. Id in product model is: id | integer | | not null | nextval('product_product_id_seq'::regclass) I have exported it in .bak file and restored it in another server. now that id is like: id | integer | | not null | nextval does not appear in the second server. what is the problem? -
Django DetailView with FormView
I want to make a comment page for post objects, where post object is using DetailView and underneath I would like to have CommentForm for adding comments. I followed along : official docs but I got stuck. I'm getting 404 error. So from the beggining, I have two models in models.py: class Post(models.Model): content = models.TextField(max_length=280, validators=[MaxLengthValidator(280)]) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='comments') text = models.TextField(max_length=280) date_created = models.DateTimeField(auto_now_add=True) Then I have my views.py: class PostDetailView(DetailView): model = Post context_object_name = 'post' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = CommentForm() return context class CommentCreateView(SingleObjectMixin, FormView): model = Comment form_class = CommentForm template_name = 'social/post_detail.html' def form_valid(self, form): form.instance.author = self.request.user.userprofile return super().form_valid(form) def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden('') # It crashes here! self.object = self.get_object() return super().post(request, *args, **kwargs) def get_success_url(self): return reverse('post-detail', kwargs={'pk': self.object.pk}) class PostDetail(View): def get(self, request, *args, **kwargs): view = PostDetailView.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = CommentCreateView.as_view() return view(request, *args, **kwargs) After little debugging I found out that it crashes while executing line self.object = self.get_object() The urls.py path('post/<int:pk>/', PostDetail.as_view(), name='post-detail'), The error itself: Page not found (404) Request … -
how to do atomic increment in django model
How can I create atomic increment in my model class IpadCode(models.Model): """ code = string """ code = models.CharField(max_length=6, blank=True, null=True) submission_index = models.PositiveIntegerField(default=0) CODE_FIELD = 'code' class Meta: verbose_name = 'ipad code' verbose_name_plural = 'ipad codes' @classmethod def increment_counter(self, code): pass def get_code(self): """ :return: return code for this winner """ return getattr(self, self.CODE_FIELD) def __str__(self): return self.get_code() I need to track how much code has been saved and count that so I can later in view redirect users if they satisfy certain criteria. -
How to create a Django Virtual Environment offline?
I am trying to build a Django virtual environment on my PC that is not connected to Internet. I have Miniconda installed on the PC. When I run this command: conda create --name MyDjangoEnv django I get an error "Conda http error" and it says that I cannot connect to https://www.anaconda.com. Do i need to download any packages from the Internet to make it work? -
Managing several services in a docker container
I am building an application where I'm using several technologies ranging from Django, Redis, Celery Worker, Postgres, Go, Vue. How advisable is it to run all this services in a single container running on one instance on AWS. Is it effective and how scalable is this approach. Please I will appreciate a better approach and recommendations. -
How to run command line inside a django view?
[Context] I have a file upload operation in my Django application (on ubuntu server), I have to execute an operation after the user uploaded the file. The tool for that is only available as a npm package (accessible via command line). What is the recommended solution for this? -
django javascript no reload
how can i change url in django with javascript without refreshing this is my code and it doesn't work // script js $(document).ready(function() { // initial $("#contenu").load("{% url home %}"); // au clic $('#lien li a').click(function() { var page = $(this).attr("href"); $("#contenu").load("html/" + page + ".html"); return false; }); }); // urls.py urlpatterns = [ path('admin/', admin.site.urls), path('index', views.index, name='index'), path('index/home',views.home name="home"), path('contact',views.contact), path('about',views.about),] -
Framework for website which is build by using Bootstrap, JQ and JS
Can we post data from html to database using python without using web framework(django)? -
How can I use "HyperlinkedModelSerializer" in Django REST API?
I got an error message: HyperlinkedIdentityField requires the request in the serializer context. Add context={'request': request} when instantiating the serializer. when I'm using API to get data. What am I doing wrong here? models.py class User(AbstractUser): username = models.CharField(blank=True, null=True, max_length=255) email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] def __str__(self): return "{}".format(self.email) class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') title = models.CharField(max_length=5) dob = models.DateField() address = models.CharField(max_length=255) country = models.CharField(max_length=50) city = models.CharField(max_length=50) zip = models.CharField(max_length=5) photo = models.ImageField(upload_to='uploads', blank=True, ) serializers.py class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('title', 'dob', 'address', 'country', 'city', 'zip', 'photo') class UserSerializer(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializer(required=True) class Meta: model = User fields = ('url', 'email', 'first_name', 'last_name', 'password', 'profile') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() UserProfile.objects.create(user=user, **profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile instance.email = validated_data.get('email', instance.email) instance.save() profile.title = profile_data.get('title', profile.title) profile.dob = profile_data.get('dob', profile.dob) profile.address = profile_data.get('address', profile.address) profile.country = profile_data.get('country', profile.country) profile.city = profile_data.get('city', profile.city) profile.zip = profile_data.get('zip', profile.zip) profile.photo = profile_data.get('photo', profile.photo) profile.save() return instance And views.py class UserList(ListCreateAPIView): ''' Return list all … -
How to update a field in a model by matching with different field in another model in django
i have a model called proposed with with three fields ,1st field(commodity) and 2nd field(rate) is being filled dynamically from views and third field (commodity_name) is empty.There is another model called list which contains two fields called com_id and com_name and both fields contain static data, what i want to do is match my proposed model's commodity field with my list model's com_id (they have same datatype) and update proposed models commodity name with list models com_name field which is in the same row as matched com_id.i need some ideas on how to do achieve this,any help is appreciated ,thank you. -
Django display posts on index page with few answers (linked by foreign key) under each one of them
I am writing an Imageboard in Django but I can't get over this basic issue how to display few answers to each post on the mainpage. I have two models, Thread and Answer, and answer is linked by foreign key to thread. I would like to display each Thread with three latest answers underneath. I would really appreciate some help here. -
Django migrate multiple databases issue
I am doing a project with Django, there are too much data so that I need to form different databases to store them. I made a database router for each app to match the unique database, but when I maigrate them, all the tables were migrate to the same database, here are the codes: from django.conf import settings DATABASE_MAPPING = settings.DATABASES_APPS_MAPPING class DatebaseAppsRouter(object): """ 该类为连接不同数据库的路由,在setting中通过设置DATABASE_MAPPING来匹配数据库 例: DATABASE_APPS_MAAPING = {"app1":"db1", "app2":"db2"} """ def db_for_read(self, model, **kwargs): """将所有读操作指向指定的数据库""" if model._meta.app_label in DATABASE_MAPPING: return DATABASE_MAPPING[model._meta.app_label] return None def db_for_write(self, model, **kwargs): """将所有写操作指向指定的数据库""" if model._meta.app_label in DATABASE_MAPPING: return DATABASE_MAPPING[model._meta.app_label] return None def allow_relation(self, obj1, obj2, **kwargs): """允许使用相同数据库的应用程序之间的任何关系""" db_obj1 = DATABASE_MAPPING.get(obj1._meta.app_label) db_obj2 = DATABASE_MAPPING.get(obj2._meta.app_label) if db_obj1 and db_obj2: if db_obj1 == db_obj2: return True else: return False else: return None def allow_syncdb(self, db, model): """确保这些应用程序只出现在相关的数据库中""" if db in DATABASE_MAPPING.values(): return DATABASE_MAPPING.get(model._meta.app_label) == db elif model._meta.app_label in DATABASE_MAPPING: return False return None def allow_migrate(self, db, app_label, model=None, **kwargs): """确保身份验证应用程序只出现在login数据库中""" if db in DATABASE_MAPPING.values(): return DATABASE_MAPPING.get(app_label) == db elif app_label in DATABASE_MAPPING: return False return None By using the router, I would like to migrate multiple databases, but it doesn't work System check identified some issues: WARNINGS: ?: (urls.W001) Your URL pattern '^login/$' uses include with a … -
Python: What is 'theweek' parameter in the formatweek() method in HTMLCalendar?
I am making a web app in Python/Django and I am trying to make a calendar that displays meetings using the HTMLCalendar class in the calendar module. I am overriding the formatday(), formatweek() and formatmonth() methods in HTMLCalendar. I have written my new code for the formatday() function. I have found two code samples for the formatweek() function demonstrating its usage: # Sample 1 def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'<tr> {week} </tr>' # Sample 2 def formatweek(self, theweek, width): """ Returns a single week in a string (no newline). """ return ' '.join(self.formatday(d, wd, width) for (d, wd) in theweek) I am not sure what theweek parameter is exactly. I have searched online for documentation for formatweek() but I could not find anything that outlined what theweek parameter is. Any insights are appreciated. -
How to get the related images in DRF?
Here I have two models and have Many-to-one relation . In the ListPackageGallery class I want to list all the images uploaded to some package. How can I query the images of some particular package here? I am very new to django rest.So am I going the right way by using the generics API view for such cases ? class Package(models.Model): name = models.CharField(max_length=255,unique=True) slug = AutoSlugField(populate_from='name') package_desc = models.TextField() class PackageGallery(models.Model): package = models.ForeignKey(Package, on_delete=models.CASCADE) image = models.ImageField(upload_to='package_gallery') serializers.py class PackageGallerySerializer(serializers.ModelSerializer): class Meta: model = PackageGallery fields = '__all__' views.py class CreatePackageGallery(generics.CreateAPIView): serializer_class = PackageGallerySerializer queryset = PackageGallery.objects.all() class ListAllGallery(generics.ListAPIView): serializer_class = PackageGallerySerializer queryset = PackageGallery.objects.all() class ListPackageGallery(generics.RetrieveAPIView): serializer_class = PackageGallerySerializer lookup_field = 'slug' def get_queryset(self): return PackageGallery.objects.filter(package=self.slug) #i got stuck here urls.py path('create/gallery/',CreatePackageGallery.as_view(),name='create_package_gallery'), path('list/all/gallery/',ListAllGallery.as_view(),name='list_all_gallery'), path('list/<slug>/gallery/',ListPackageGallery.as_view(),name='list_package_gallery'), -
Django How do i display different pages on one html
I am currently making a movie reservation site using django. The first page lists the currently screened movies. If I click on one of them, then go to the page where shows the details of the movie. If there are movie A, B, and C that is currently being screened. For example If I click A, I want to have detailed information about A movie on the movie details information page. If I click B, I want to have detailed information about B movie on the movie details information page. If I click C, I want to have detailed information about C movie on the movie details information page. I want to make it not using javascript!! only using django and html!! Could you please help me? moviehome.html / Showing Current playing movies and Coming soon movie <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Current Playing</h1> Hi, {{user}}! <a href="{% url 'signout' %}">LOG_OUT</a><br> {% for movieinfos in movie.all %} <a href="{% url 'realinfo'%}"><img src="{{movieinfos.movie_poster.url}}" width=100px height=150px></a><br> {{movieinfos.movie_age}} <a href="{% url 'realinfo'%}">{{movieinfos.movie_name}}</a><br> 장르 | {{movieinfos.movie_genre}}<br> 감독 | <a href="{% url 'directorinfo' %}">{{movieinfos.movie_director}}</a><br> 출연 | <a href="{% url 'actorinfo' %}">{{movieinfos.movie_actor1}}</a> , <a href="{% url 'actorinfo' %}">{{movieinfos.movie_actor2}}</a> <br> {% endfor … -
Django / Bootstrap 4 / Blog Post || How to get responsive images?
I've been able to add images to my post with ckeditor which is great but I can't seem to get the images to shrink and be responsive like the rest of the content/text in my post. I've tried a few tutorials and played around with things but nothing seems to work. Thanks. Here is my BASE.HTML {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'portfolio_app/main.css' %}"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Davi Silveira DoP</title> </head> <body> <main role="main"> {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} {% block content %}{% endblock %} </main> <footer class="text-muted"> <div class="container"> <p class="float-right"> <a href="#">Back to top</a> </p> <p class="text-muted">Davi Silveira &copy; 2020</p> <p>Associated with <a href="https://www.facebook.com/silveirabrothers/">Silveira Brothers Films</a></p> </div> </footer> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> BLOG.HTML {% extends "portfolio_app/base.html" %} {% block content %} <div class="container"> <div class="row"> <div … -
How can i fix django rest framework metaclass conflict
i am a beginner learning django rest framework and i just encounter this error and i cant seem to find a way around it, please i need gurus to help me out. Here is the permissions.py sample code from rest_framework import permissions class UpdateOwnProfile(permissions, BaseException): """Allow user to edit their own profile""" def has_object_permission(self, request, view, obj): """Check if user is trying to update their own profile""" if request.method in permissions.SAFE_METHODS: return True return obj.id == request.user.id Here is also a sample of the views.py sample codes from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets from rest_framework.authentication import TokenAuthentication from profiles_api import serializers from profiles_api import models from profiles_api import permissions class HelloApiView(APIView): """Test Api view""" serializer_class = serializers.HelloSerializer def get(self, request, format=None): """Returns a list of Api features""" an_apiview = [ 'Uses HTTP methods as function (get, post, patch, put, delete)', 'Is similar to a traditional Django view', 'Gives you the most control over your application logic', 'Is mapped manually to URLs', ] return Response({'message': 'Hello', 'an_apiview': an_apiview}) def post(self, request): """Create a hello message with our name""" serializer = self.serializer_class(data=request.data) if serializer.is_valid(): name = serializer.validated_data.get('name') message = f'Hello {name}' return … -
How do I launch custom application on client machine from Django web page
I am writing a Django based web application. Following is what I need to achieve Check if the custom application is already installed on the client machine (mostly Windows based) If the application is installed then launch the same from the web page If not installed, push the application to client machine from the web page for user to install (Done) Upon clicking on the stop button on webpage the application on client machine should stop I am reading more about deeplink on web for same, however most of it is for mobile browsers and app is in mobile device If anybody has done this, I would really appreciate if you share the design approach. -
What is the 'to=' positional argument in ForeignKey?
In my project (I am learning Django, so it's a very basic one) I am trying to implement a relationship such as 'an order can have multiple meal items'. So after checking the documentation, I realised that this can be rather implemented as 'a meal item can be in one ore more orders' through the use of the ForeingKey field class. On the Django documentation page for ForeignKey it is said: 'Requires two positional arguments: the class to which the model is related and the on_delete option.' But just passing these two arguments and trying to make the migrations throws an error: TypeError: __init__() missing 2 required positional arguments: 'to' and 'on_delete' Now, my Meal class in models.py looks like so: class Meal(models.Model): name = models.CharField(max_length=15) price = models.DecimalField(max_digits=4, decimal_places=2) order = models.ForeignKey(Order, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('meals:detail', kwargs={'id': self.id}) I think the problem is due to the fact that the two classes (Order and Meal) are implemented as two different apps (not even sure if that's the way to organise things for reuse). So back to the documentation, when I look to the arguments for ForeignKey it doesn't say anything about the to= positional argument. … -
How to use the GET method in order to fetch data that's saved in the POST method via Django DRF API call?
I want to create an API that allows me to save an image using the POST method via APIView in Django Rest Framework. The image that's saved in the POST method should be displayed within the GET method in the API webpage. The image that's stored is not saved in a model but in a local directory. I don't wish to grab the image name from the directory via the GET method since I will be saving image(s) in a server in the near future. However, I would like to make the process dynamic enough so that the GET method can capture/fetch the image name data immediately after a user uploads and submits an image using POSTMAN. How can this be done? Currently, this is what I had done so far: class API(APIView): parser_classes = (MultiPartParser,) #Need to display the image name here that was saved using the POST method below. def get(self, request, *args, **kwargs): image_filename = self.request.GET.get('image') return Response({'image_name' : image_filename}, status=200) def post(self, request): #key is 'image', value is the file uploaded in the system data = self.request.data #image that gets uploaded img_file = data['image'] if img_file: uploaded_file = img_file image = [{"image_name": uploaded_file}] return Response(image, status …