Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python (Django) running code in main thread
I am trying to use requests_html to parse HTML page that requires javascript rendering. Thing is I get the request to start the whole process in a Django view request which runs in another thread. This makes everything complicated, since it seems there is no well defined way of spawning things in main thread as there is in Android (Java) for example ( activity.runOnUiThread( callback... )). There are loops and queues, but I could not find a single explanation of how to signal Python (Django's?) main loop to run a callback! Not to talk about waiting for it to finish in that other thread. I am sure there is a method of doing so without invoking a whole seperate process (AKA multiprocessing) - I know this option. It is a heavy solution, which I use, but it requries transfering data in <-> out of the child process in ugly ways. So... Can I run code in Python's (Django server) main thread looper? -
Dfango function view VS class RedirectView. How to make class view accept arguments
Function as a view knows question, but class does not (args,kwargs are from url, empty, post method has only choice , but not question). Both work, but for adding checks I would like to know how to get question in class. Its init or get_redirect_url or request have nothing inside like question_id url.py from django.urls import path from . import views app_name = 'polls' ulrpatterns=[ path('<int:question_id>/vote/', views.vote, name='vote'), path('<int:pk>/vote0/', views.vote0.as_view(), name='vote0'), ] views.py class vote0(generic.base.RedirectView): pattern_name = 'polls:results' def get_redirect_url(self, *args, **kwargs): selected_choice = get_object_or_404(Choice, pk(self.request.POST['choice'])) selected_choice.votes +=1 selected_choice.save() return super().get_redirect_url(*args, **kwargs) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) selected_choice = question.choice_set.get(pk=request.POST['choice']) selected_choice.votes += 1 return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) -
Elastic Beanstalk won't find/use my requirements.txt file and so it cannot find the module "django"
I'm trying to deploy a python web app using django and have successfully setup the EB environment but for some reason, it's not using my requirements.txt file to install the required modules (django and pytz). I see no reference to an invalid requirements.txt so I don't think that's the issue. Here is a file hierarchy and the latest log. FirstWebApp/ .elasticbeanstalk/ config.yml mysite/ #.. polls/ #.. db.sqlite3 manage.py requirements.txt [Sat Sep 01 21:08:01.508757 2018] [mpm_prefork:notice] [pid 7866] AH00169: caught SIGTERM, shutting down [Sat Sep 01 21:08:02.599699 2018] [suexec:notice] [pid 11160] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Sat Sep 01 21:08:02.615594 2018] [so:warn] [pid 11160] AH01574: module wsgi_module is already loaded, skipping [Sat Sep 01 21:08:02.617699 2018] [http2:warn] [pid 11160] AH10034: The mpm module (prefork.c) is not supported by mod_http2. The mpm determines how things are processed in your server. HTTP/2 has more demands in this regard and the currently selected mpm will just not do. This is an advisory warning. Your server will continue to work, but the HTTP/2 protocol will be inactive. [Sat Sep 01 21:08:02.617712 2018] [http2:warn] [pid 11160] AH02951: mod_ssl does not seem to be enabled [Sat Sep 01 21:08:02.618263 2018] [lbmethod_heartbeat:notice] [pid 11160] AH02282: No slotmem … -
Connecting to website via domain regirects to IP(no guides nor "fixes" helped)
I am using GoDaddy domain and connectiong it to django+gunicorn+nginx droplet hosted on DigitalOcean. After all tried configs of DO, nginx, etc., I'm still getting the same result. When I'm trying to connect via domain, it changes it to IP address and proceeds... Last nginx config I stopped on is: server { listen 80; server_name example.com www.example.com ip.ip.ip.ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/webapp; } location /media/ { root /home/user/webapp; } location / { include proxy_params; proxy_pass http://unix:/home/user/webapp/webapp.sock; } } -
How to use single Django Template for multiple purpose
I have different django models which are identical e.g ItemCategory InventoryCategory MenuCategory ExpenseCategory All of these models carry same attributes. I want to use single html page which is category_list.html for displaying these models as list. I don't want to use different pages like item_category_list.html, inventroy_category_list.html, menu_category_list.html and so on. Every page contains page header which is actual kind of title of page represented in h1 tag. I want to change with respect to currently loaded page. Note: I am using Generic Views for Listing Items and I am currently using context for recognizing which view is sending response. Any help would be appreciated. -
Running Python Script(of Jupyter) in Django
I have written a piece of code in Jupyter notebook, Is it possible to run that script file from Django and get the results without installing those packages and modules that were imported in order to write the code in jupyter notebook file? -
RelatedObjectDoesNotExist error inspite of using if statement
I have the below code if self.request.user.is_authenticated() and self.request.user. userlocation What I don't understand is why I am getting this User has no userlocation error. I have a if statement if he condition is not met should it not just go down and show the context class Homepage(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super(Homepage, self).get_context_data(**kwargs) context['event_list'] = Event.objects.all() if self.request.user.is_authenticated() and self.request.user.userlocation: print("The code reached here ") return context -
Use django-crispy-forms with Uikit
I'm building a website with django and i'm using uikit 3 as front-end framework is there any way to style django-crispy-forms with uikit ? with bootstrap i can just put this line on settings file : CRISPY_TEMPLATE_PACK = 'bootstrap4' is their any option like this to use uikit ? -
Why do I get connecting the library path in Django?
When I adding the library path in app general of urls, send me the next message: "E0611:No name 'path' in module 'django.urls'" and "E0611:No name 're_path' in module 'django.urls'". It is the code in generals urls: from django.contrib import admin from django.conf.urls import url,include from django.urls import path,re_path from homepage.views import homepage urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^',include('homepage.urls')), ] urlpatterns +=[ url(r'?P<path>,*)',homepage.as_view(),name='home') ] Thanks for you help me. -
Can't update static files in s3 via django
I want to update some CSS files I have modified locally for a django application. The first time I ran collect static it worked fine and it uploaded the files to the S3 bucket. Now I'm running it again and I receive the following message for all files: "Found another file with the destination path 'whatever'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path." My settings file imports this from my conf.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) AWS_ACCESS_KEY_ID = "whatever" AWS_SECRET_ACCESS_KEY = "whatever" AWS_STORAGE_BUCKET_NAME = 'xxx' AWS_S3_CUSTOM_DOMAIN = '%s.s3.us-east-2.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # media MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) # MEDIA_ROOT = '' # <-- no bad request 400 MEDIA_ROOT = os.path.join(BASE_DIR, 'temp_media') # <-- bad request (400) And the tree of my project is as this one: project -botApp -aws -conf.py -settings.py -static (here I modified my files locally) Many thanks -
Perform Django ORM aggregation over jsonb fields
I've run through all Django sources about aggregation, still can't understand how to implement the following query with Django ORM. This query will output the count of houses per each color: select clr.id as colorId, count(*) as count from colors as clr inner join houses as c on clr.id = cast(c.parameters ->> 'colorId' as int) group by colorId; Data schema is defined as follows: CREATE TABLE colors ( id int primary key, name text NOT NULL ); CREATE TABLE houses ( id bigserial primary key, parameters jsonb NOT NULL ); insert into colors (id, name) values (1, 'red'), (2, 'green'), (3, 'blue'), (4, 'other'); insert into houses (parameters) values ('{"price": 1000, "colorId": 1}'), ('{"price": 2000, "colorId": 2}'), ('{"price": 2500, "colorId": 2}'), ('{"price": 3000, "colorId": 3}'), ('{"price": 3100, "colorId": 3}'), ('{"price": 3200, "colorId": 3}'); What would be implementation with Django ORM? Simple queries are pretty straightforward, but I miss something to understand about aggregation over jsonb fields -
Django ModelForm hide field from form and use value from url
Thanks in advance for reading this. I can't wrap my head around it and it's getting quite frustrating by now. We have the following registration form: class RegistrationForm(forms.ModelForm): class Meta: model = Register fields = ('name', 'company_name') def clean(self): if is not self.cleaned_data.get('card').is_available(): raise forms.ValidationError(_('Error')) The Register model includes a card linked to a Card model. This includes is_available() which functionally works. Our flow is: The end user selects the card which lists all registrations for it. They click the 'Add registration'-button which brings them to cards/{PK}/add. The Add registration-button is a generic.View. In post(self, request, pk) I have the following code: form = RegistrationForm(request.POST) But how do I pass it the contents of Card.objects.get(pk=pk) to it? I tried: data = request.POST.copy() data['card'] = pk form = RegistrationForm(data) But I think because card is not included in fields it gets lost somewhere, which makes sense from a sanitize-all-input-point of view, but I would very much like to add the card dynamically, in this case. Any ideas? -
Django "adminlike" foreign key add button
So I have a delivery model with a foreign key relation to customer. I would like to introduce the "add foreign key" button, just like the admin area does. I've read the thread on the custom widget showed here: Django: adding an “Add new” button for a ForeignKey in a ModelForm Unfortunately I couldn't get it working, so I tried a different approach. In the delivery form, I've added a "Add Customer" button. This button opens up a modal which shows a form to add a customer with ajax. So I got the form working, it adds a new customer to the database without leaving the delivery form area. The trick is, I would like to have the newly added customer selected in the customer dropdown. I need have to retrieve the customer.id from the newly created customer and select him or her in the dropdown, this is were I'm stuck. The ID is not available in the customer form yet so I would have to retrieve it from the database with GET... Any thoughts about this? Any help would be greatly appreciated! urls.py urlpatterns += [ # Links to create, update and delete deliveries url(r'^delivery/create/$', login_required(views.DeliveryCreate.as_view()), name='delivery_create'), url(r'^delivery/add_customer/$', login_required(views.delivery_add_customer), … -
Makemigrations Django probleme
When i run makemigrations in django i got the error : Error Image and this is my code : from django.db import models class List(models.Model): name = models.CharField(max_length=50) def __str__(self): return "List:{}".format(self.name) class Card(models.Model): title = models.CharField(max_length=100) description = models.TextField(blank=True) list = models.ForeignKey(List, related_name="cards") story_points = models.IntegerField(null=True, blank=True) business_value = models.IntegerField(null=True, blank=True) def __str__(self): return "Card:{}".format(self.title) -
Django: generic UpdateView use slug instead of pk
The code for using the pk is the following: views.py class CreatorUpdate(LoginRequiredMixin, UpdateView): model = Creator fields = ['first_name', 'last_name', 'location', 'country'] success_url = reverse_lazy('index') # these two methods only give access to the users own profile but not the others (prevents url hacking) def user_passes_test(self, request): if request.user.is_authenticated: self.object = self.get_object() return self.object.user == request.user return False def dispatch(self, request, *args, **kwargs): if not self.user_passes_test(request): return redirect_to_login(request.get_full_path()) return super(CreatorUpdate, self).dispatch(request, *args, **kwargs) urls.py path('creator/<int:pk>/update/', views.CreatorUpdate.as_view(), name='creator-update') HTML snippet to call the URL: <a href="{% url 'creator-update' user.pk %}">{{ user.get_username }}</a> Now I would like to use a slug (username) instead of the pk to access the UpdateView. I can successfully pass the username to the URL: <a href="{% url 'creator-update' user.get_username %}">{{ user.get_username }}</a> but seem not to be able to match it in urls.py (path('creator/<slug:slug>/update/', views.CreatorUpdate.as_view(), name='creator-update')) with the same logic. I also tried to set a SlugField in my Creator model like this: from django.template.defaultfilters import slugify class Creator(models.Model): ... username = models.CharField(max_length=100) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = slugify(self.username) super(Creator, self).save(*args, **kwargs) ... And setting slug_field = 'slug' in the UpdateView also does not get it. What is the logic to use a … -
Import Error in python even if file exist
Though the file exist and is imported, when I press ctrl and hove over it, pop up shows up in pycharm. Why am I then getting ImportError? I am using Django and the content of file looks like: I looked at a few questions where suggested way is: import sys print(sys.path) If file doesn't exist, shall not pycharm complain of it? rather it suggest me for the functions as: -
How to make a query based in a FK?
I have two models. in my View, I want a return what reference Model1 to Model2, filtering the user logged attributed a ModelTwo. Here is my models.py ModelOne(models.Model): name = models.CharField(max_length=64, unique=True) description = models.TextField() ModelTwo(models.Model): model_one = models.ForeignKey(ModelOne, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) In my view, I want a result get user has attributed ModelTwo getting PK to ModelOne. I tryied this, but the PK is getting is the ModelTwo, and I want PK for ModelOne: def get_queryset(self): return ModelTwo.objects.filter(user=self.request.user) I saw '__'(underscore, underscore) to make querys about another classes(FK), but I did not make it. Another thing, is related_name, with have a form to make with this, its interesting to use. Can anyone help me? Thanks a lot for your attention my friends. -
Django nested Serializer filter to only one field, not all fields
I have two serializers like below. The output for the below snippet is Workers and with associated Ticket Counter details with all fields (ticket_counter,ticket_counter_name,worker). But I just need only one field that is ticket_counter_name. class WorkerSerializer(serializers.ModelSerializer): ticket_counter = WorkerToCounterSerializer(many=True, read_only=True) class Meta: model = User fields = ( 'username', 'ticket_counter', ) class WorkerToCounterSerializer(serializers.ModelSerializer): ticket_counter = SerializerMethodField() ticket_counter_name = serializers.CharField(source='ticket_counter.ticket_counter_name') class Meta: model = WorkerToTicketCounter list_serializer_class = FilteredListSerializer fields = ( 'ticket_counter', 'ticket_counter_name', 'worker', ) def get_ticket_counter(self, obj): return obj.ticket_counter.pk class FilteredListSerializer(ListSerializer): def to_representation(self, data): data = data.filter(worker_to_ticket_counter_is_deleted=False)[:1] return super(FilteredListSerializer, self).to_representation(data) What above snippet outputs { "username": "xxxxxxxxxxx", "ticket_counter": [ { "ticket_counter": 7, "ticket_counter_name": "Entrance Counter", "worker": 4, } ] } But What I want is { "username": "xxxxxxxxxxx", "ticket_counter": "Entrance Counter" } I just need the name of the ticket_counter_name. Is it possible? -
How to make an interactive weather reporting web server with python?
I am trying to make a website that I can run on my raspberry pi which will allow me to input the name of a city, and be given weather information for that city. I already know how to get the actual data for the users requests with an API however I do not know the best way to make a nice looking webserver to accept input and present the data to the user. I have done some research and it seems as though Django/flask are options but I have no experience with them. Are these the best way to do what I have described or is there a better way? Thanks. -
How to display arbitrary images of a server in Django 2.1?
Have a web interface. I can select any path of the server on the web interface. Display all the images in this path to the web interface. try: 1. I can't use these images as static resources. 2. If I take the absolute path of the image as the 'src' of the tag, it will cause the image 404 error. what shoud I do if I want to make this image's url correct -
Django: display textfield on dropdown select
i am doing an app in django for adding certain articles into the database. Right now i have it made so you can either select a category from dropdown or add a new category into a text field that is sitting under the dropdown. Now i would like to change it so that text field is hidden until you select "add new category" in a dropdown. Is there an option to do this with django alone, without adding javascript ? -
How to Link Django with Android Application?
I was recently given the task of assisting the production of an Android Application. Specifically, this app will be built using Java in Android Studio with a Realtime Firebase Database to handle it's data. I was told to learn Django for the backend. The truth is I am not sure how Django helps in the backend and what I need to do for Linking Firebase and the Application. In short why would we use Django here? -
Django ORM - get queryset of related items
Consider the following models: class Car(Model): owner = ForeignKey(User) ... some irrelevant attributes ... class User(Model): # Django user model Given a queryset of users, is there an easy way (e. g. one method call) how to get a queryset of cars which are owned by a user from the first queryset? Something like User.objects.all().related("cars"). -
Can I query a secondary database from Django without ORM?
I need to query a database controlled by another application from my Django application. Ideally I'd also like to modify a few values. I've configured a secondary database connection from within Django, but because the tables are controlled elsewhere, they don't fit neatly into Django's ORM. I'd rather make simple SQL queries from within my Django application. Is this possible? -
Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['articles/edit/(?P<pk>[0-9]+)/$']
I am a beginner in Django and now i am developing a blogging application. At the article editing section i got stucked and I dont know why its showing this error. Searched a lot and cant find an answer NoReverseMatch at /articles/edit/2/ Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['articles/edit/(?P<pk>[0-9]+)/$'] edit_articles section in views.py @login_required(login_url="/accounts/login/") def edit_articles(request, pk): article = get_object_or_404(Article, id=pk) if request.method == 'POST': form = forms.CreateArticle(request.POST, instance=article) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('articles:myarticles') else: form = forms.CreateArticle(instance=article) return render(request, 'articles/article_edit.html', {'form': form}) article_edit.html {% extends 'base_layout.html' %} {% block content %} <div class="create-article"> <form class="site-form" action="{% url 'articles:edit' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="jumbotron"> <div class="heading col-md-12 text-center"> <h1 class="b-heading">Edit Article</h1> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> {{ form.title }} </div> </div> <div class="col-md-6"> <div class="form-group"> {{ form.slug }} </div> </div> <div class="col-md-6"> <div class="form-group"> {{ form.thumb }} </div> </div> <div class="col-md-12"> <div class="form-group"> {{ form.body }} </div> </div> </div> <button type="submit" class="btn btn-primary btn-lg btn-block">Update</button> </div> </form> </div> {% endblock %} urls.py from django.urls import path from . import views app_name = 'articles' urlpatterns = [ path('', views.article_list, name='list'), path('create/', views.article_create, name='create'), path('edit/<int:pk>/', views.edit_articles, …