Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check duplicate posts when submitting a new post in Django admin?
I have coworkers to upload posts through Django admin. The problem is they keep making duplicate posts as we've been covering a lot of posts. Is there a way to find out if a post already exists when typing a certain column or submitting? I searched about that, but didn't get any useful information. -
django fsm doesn't save model if an exception happens
I've got a weird problem that has been bugging me for a bit that I'm hoping to get some help with. I'm using Python 3.6, Django 1.11, Celery 4.2.1, and Django-fsm 2.6.0. I have an application that does callbacks to external sites using requests and will save the results of the callback to a model to track them. This is all done via Celery. The problem that I'm running into is that if I get an exception back when trying to send the callback, when handling that exception I'm not able to save the state of the model that is using fsm. Here is my code inside the celery task that is calling the transaction callback manager: try: manager.setup_callback() manager.make_callback() except business_exceptions.BusinessConfigurationException as exc: logger.warning( f"Problem setting up callback: {exc} won't try again.", exc_info=True ) except business_exceptions.TooManyCallbackRequestsException: logger.info( f"There is a current callback ongoing for this one. Skipping this." ) except (Exception, BaseException) as exc: logger.warning(f"error of {exc}", exc_info=True) self.retry(countdown=callback_retry_delay(self.request.retries), exc=exc) Here is the try except inside of the make_callback() method: try: response = self.post_without_auth(data) except (Exception, BaseException) as e: message = f"Could not connect to callback endpoint: {e}" self.transaction_callback.response_raw = message self.transaction_callback.make_failed() self.transaction_callback.save() logger.debug(f"transaction status is: {self.transaction_callback.state}") raise business_exceptions.BusinessConfigurationException(e) … -
Python3 Django - Why Wont My Comments Page Render With Required/Proper Data After Comment Delete?
So I was trying to create a simple user login, message and comments board. Now everything works flawlessly, except for when I try to delete a comment.. I am able to delete messages fine, as it's a simple delete function and a redirect. but, for the comments, it's a bit different. How it works, is you log in, then taken to root which is every users message they've posted. On those messages, it allows the user to reply, which brings them to the page that shows the message information above, and comments below with a form to enter your own as well. Now the comments work , everything works, but when I delete the comment (Which yes there is an if statement to only show said comments delete button if they are the creator.) it renders the comment page, but has no data... the message content is blank and there are no comments.. I go back and refresh, to comment was deleted, and everything renders fine. SO the issue, is when it goes to my delete comment function, and then from there which was my attempt to gather all needed info from said function while simultaneously deleting the comment, sending … -
How to query db to get all objects that match a list of parameters, instead of just the last item in the list
I have a Job object and each one has a zip_code field. I am trying to loop through a list of zip codes and get all matching Job objects. But with my current query, instead of appending the additional Job objects to jobs_matching_query, jobs_matching_query is reset every time, leading to only the Job objects with the last zip code in the list (10564 in the bottom example) being returned. How can I query my db so that all Job objects with zip codes in zip_codes_within_15_mile_radius are returned? my code: zip_codes_within_15_mile_radius = ['10535', '10579', '10564'] for zip_code in zip_codes_within_15_mile_radius: jobs_matching_query = Job.objects.filter(zip_code__iexact = zip_code) #this query only returns jobs that have '10564' as their zip code -
How to call all the subclasses using foreign key in base class in Django?
In my models, I have a base class that has a foreign key to another table. This class is extended by 2 other models. Its something like this: class Foo(models.Model): ... class Base(models.Model): foo = models.ForeignKey(Foo, related_name='bases') class A(Base): ... def bar(self): print "A" class B(Base): ... def bar(self): print "B" Now, let me explain what I want to do. Lets say I get an instance of the Foo class using foo=Foo.objects.get(pk=1), I want to then call the bar() method for every object of every subclass of Base, provided they have a relationship to foo. Something like this: class Foo(models.Model): ... def call_all_bars(self): for base in self.bases.all(): base.bar() Obviously, this does not work. The related name seems to be an issue. Is there any way to do this? Or do I have to set unique related names for each subclass and call every one of them in my method? Thanks. -
How to reorder Django-Graphene sub-query?
I am trying to reorder my ProductLandingPageImageNode according to a 'order' field on my ProductLandingpageImage Model. If this would be a direct query I could write a resolve method, but I cannot find out how this is possible on a sub-query. MAIN QUERY: class Query(graphene.ObjectType): class Meta: interfaces = [relay.Node, ] product_oscar = graphene.List(ProductNode) productByID = DjangoFilterConnectionField(ProductNode) def resolve_product_oscar(self, info, **kwargs): return Product.objects.all() PRODUCTNODE: class ProductNode(DjangoObjectType): class Meta: model = Product interfaces = (relay.Node, ) filter_fields = { "slug" : ['iexact'] } PRODUCTLANDINGPAGEIMAGENODE: class ProductLandingpageImageNode(DjangoObjectType): class Meta: model = ProductLandingpageImage interfaces = (relay.Node, ) How to solve this? -
Connect Otree Project to MySQL
I'm trying to connect my Otree project to MySQL database, but whatever I do it doesn't replace the default database (which is SQLite) with MySQL. When I run the command otree runprodserver 80 and try to access localhost:80 I get the following message: Your database is not ready. Try running 'otree resetdb'. (Missing tables for otree.FailedSessionCreation, otree.ChatMessage, sessions.Session, and 15 other models). (obviously running 'otree resetdb' does not solve the problem.) I added the following lines to settings.py : environ['DATABASE_URL'] = 'mysql://localhost:3306' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DBNAME', 'USER': 'DBUSER', 'PASSWORD': 'DBPASSWORD', 'HOST': 'localhost', 'PORT': '3306', } } but it still doesn't work. Any ideas what can I do to solve the problem? Thanks. -
django form not submitted in database
I am trying to submit data using model popup form using django models.py from django.db import models from django.urls import reverse class CollegeMaster(models.Model): college_name = models.CharField(max_length = 250,unique=True) college_initials = models.CharField(max_length=100,unique=True) logo = models.FileField() def get_absolute_url(self): return reverse('college_master:index') def __str__(self): return self.college_initials This is my view class for creating college details. views.py class CollegeCreateView(PassRequestMixin, SuccessMessageMixin,generic.CreateView): template_name = 'college_master/create_college.html' form_class = AddClgForm success_message = 'Success: Book was created.' success_url = reverse_lazy('college_master:index') index.html {% extends 'base.html' %} {% block title %}College Master{% endblock %} {% block body %} {% include "college_master/_modal.html" %} <div class="container-fluid"> <!-- Breadcrumbs--> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="{% url 'home' %}">Dashboard</a></li> <li class="breadcrumb-item active">College Master</li> </ol> <!-- Form Content Start--> <div class="col-12 mb-3"> <button class="create-college btn btn-primary" type="button" name="button"> <span class="fa fa-plus mr-2"></span>Create College</button> </div> <!-- Form Content End --> </div> {% endblock %} {% block extrascripts %} <script type="text/javascript"> $(function () { // Create book button $(".create-college").modalForm({formURL: "{% url 'college_master:create_college' %}"}); }); </script> {% endblock extrascripts %} This is main html file where form content is placed and when user submit on click data is not reflected to database. create_college.html {% load widget_tweaks %} <form method="POST" action="{% url 'college_master:index' %}" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-header"> <h3 class="modal-title">Create … -
Why does Modal Box disappear after the web page finishes loading?
I am trying to show search result(using Django search) in a Modal box. Hopefully, when a user clicks the "search" button, a Modal box will pop up and the result will be displayed in the Modal box. Now, after I click the "search" button, "?q=XXX" will be added after the current URL, and a Modal box with the result will show up while the page is still loading the new URL. However, once the page finishes loading the new URL, the Modal box will disappear. Why does this happen, and how can I fix it? Huge appreciation in advance. HTML template <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel='stylesheet' href="{% static 'css/inText_Search.css' %}" /> ... ... <form method="GET" action=""> <input type="text" value = '{{ request.GET.q }}' name ='q' placeholder="Search within this manuscript..." style="display:inline-block; width:55%"> <button class="btn btn-success" type="submit" data-toggle="modal" data-target="#searchModal"> search </button> </form> <div class="modal fade" id="searchModal" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <span class="close" data-dismiss="modal">&times;</span> <p><font color = 'red'>{{ request.GET.q }}</font> found on: <ul> {% for found_page in search_result %} <script type=text/javascript> var found_page_number='{{found_page.id_tei}}' var found_page_number = found_page_number.slice(-3) console.log('found on'); console.log(found_page_number); </script> <li> <a href="/page/{{found_page.id_tei}}"> Page <script type='text/javascript'> document.write(found_page_number) </script> </a> </li> {% endfor %} </ul> </p> </div> </div> … -
Edit approved email points to localhost
After approving a change in the Wagtail admin, the editor receives an email letting them know the page is published. The problem is the link to the page doesn't use the site domain, but localhost: You can view the page here: http://localhost/learn/good-stuff-to-learn/ I have both BASE_URL and WAGTAILAPI_BASE_URL configured in my settings.py. Is there another setting I missed? Django 1.11.10 Wagtail 1.13.1 -
how to use PIPENV_VENV_IN_PROJECT
I want pipenv to make virtual environment in the same folder with my project(django) i searched and found this 'PIPENV_VENV_IN_PROJECT' but i don't know where and how to use this option thank you -
Django celery and channels example
I have a Django app and need to generate files that can take up to a minute, so I pass that off to a background worker. Currently, the process works as follows. I post to the server that replies with a URL that I can poll. I then poll the server every 2 seconds and either sends back "busy" or a url of where the file is located in my S3 bucket. I want to replace this polling with Django channels, but unsure what is the best way to achieve this as I can't find any examples online. is channels even intended for something like this? My current thoughts are the following: Start the file generation as soon as the client opens a connection to on a specific route (previously this would have been a post) The background task gets started as soon as the client connects and get the channel name as a paramenter Once it is done it sends back the file path to the consumer which in turn sends it to the browser where I'll use JS to create a download button. Below is an example: @shared_task def my_bg_task(channel_name): #some long running calc here channel_layer = get_channel_layer() … -
How to make non-editable fields appear when creating objects in Django admin?
I have a model with a non-editable field in my models file. class Table(models.Model): label = models.CharField(max_length=40, editable=False) In my admin site, when updating existing Table objects, I can't edit the label. That is fine, this is exactly what I want with this constraint. However, when trying to create an object using the admin site, the field is still hidden, so I can only create Table objects using the shell. How can I make this field appear only on creation, but on updates, it will be read-only? Thanks. -
Why does html5 video tag does not work in Firefox even if I'm using the right format?
I was trying to add a video to my web page with tag, but the tag doesn't work correctly. Here is the code: <video src="/static/videos/test1.webm" type="video/webm" controls></video> In the web-player I get "No video with supported format and MIME type found" error. In the Internet some people say that it is the server problem and the main problem is in .htaccess server file. But I'm using Django default web-server and there is no such file here. How can I solve this problem? -
Prevent get_valid_filename() from changing the filename of a file
I am migrating to Django a site that has a large set of files that are already uploaded on AWS. Some of these files have special characters or blank spaces, that Django overwrites, which then makes the files not available. Example (original_name > django_name): unnamed (19).jpg > unnamed%20(19).jpg I have tried to use a custom storage backend with: class MyFileStorage(FileSystemStorage): def get_valid_name(self, name): return name and in my models: file = models.FileField(upload_to='files/, max_length=255, storage=MyFileStorage()) but it doesn't help, the files with special characters are still renamed by django. Any suggestion? -
Accessing a django model template page using reverse_lazy
I have a model named Lal in my django. I have successfully registered it in my admin.py file. Now , what I want is if a particular url is hit then, I should be able to directly redirect using reverse_lazy to the page displaying the model contents that I had registered in admin.py file. The url that gets generated when I access the model displaying template page using my admin-login directly is: http://127.0.0.1:8000/admin/test1_app/lal With the help of this line of code: url(r'yahoo/$', RedirectView.as_view(url = reverse_lazy('admin:app_list',kwargs={'app_label': 'test1_app'})), name="yahoo") I am able to successfully generate the following url: http://127.0.0.1:8000/admin/test1_app/ What should I add more to generate the main url i.e. this one : http://127.0.0.1:8000/admin/test1_app/lal -
How do I create a Django Login in Wordpress?
I have a Django website I also recently created a WordPress website to advertise the company. In the WordPress website, I created a custom login popup that makes the login request to Django gets the tokens and then redirects to the Django System. But when it gets to Django the cookies with tokens are not set and the user is requested to log in again. Any Idea why? Is there a configuration I should set? Thanks for the help -
Add file fields to a django model based on a related model
I have a model where you can define data sources. It's more or less a fixed list but I would like it to be adjustable in the django-admin application, hence its a model. Now I want to create a FileField that will allow uploading the specific file defined in the DataSource model with data that will be saved in details for further process. And finally there should be a form that will be building the FileInput widgets. However I don't find anywhere a solutions or at least a hint how to go forward. Can someone help here? class DataSource(models.Model): data_source = models.CharField(max_length=20) details = models.ForeignKey("Details", on_delete=models.CASCADE, related_name="data_sources") def __str__(self): return self.data_source class Details(models.Model): files={} member = models.CharField(max_length=20, null=False) date = models.DateField() data_sources = models.ManyToManyField(DataSource) for source in data_sources.some_iterator: files[source] = models.FileField(null=True, upload_to='data/') -
When does django calculate properties that aren't stored in the DB
Quick question about performance. Let's say we have some model: class MyModel(models.Model): number = models.IntegerField(default=0) def getComplicatedNumber(self): # do some complex calculations here, including other db calls return 0 # really return the complex calculation otherNum = property(getComplicatedNumber) Then let's say we have in a view: modelObject.otherNum or in a template: {{ modelObject.otherNum }} My question is, when is this attribute/property calculated when an object with the property is created? Is it only calculated when it is called in the view or template, or is it calculated whenever that object is retrieved or when an instance of that class is created? I imagine this would slow down performance if it is being calculated often and not used in views or templates. Thanks -
SyntaxError: keyword can't be an expression in django
new_todo = Todo(text=request.POST['text'],instance.User=request.user) SyntaxError: keyword can't be an expression What exactly went wrong here? I just want the user who created the todo his name should be automatically relfected to the database.....So, I have done this in my create view... -
How to detect Previous Site URL (Another website) in Django?
I am trying to implement theming for my Django site. And the theme is being dependent on the colors of the website from which request is redirected to mine. I have already tried: request.META.get('HTTP_REFERER') But that. doesn't work and returns None if the user came from another website I had visited "Sites" framework from Django, but that doesn't help either. I am not sure if it is possible yet with any package or without. I found a way via JavaScript from this post, but it is not working out for me. Is there any reliable way via Django or a pythonic approach? -
Bulk insertion in Django
I have a Django app and postgres db. I am doing bulk insertion like this: class TestListSerializer(serializers.ListSerializer): """ This class only be used once we are dealing with multiple object creation in a list fashion by having only single query for the whole insert. :returns: the number of inserted records. """ def create(self, validated_data): records = [test(**item) for item in validated_data] if test.objects.bulk_create(records): return len(records) else: return 0 class TestSerializer(serializers.ModelSerializer): class Meta: model = test fields = ('date', 'arg1', 'arg2', 'arg3', 'arg4', 'arg5') list_serializer_class = TestListSerializer So far it works fine. However I want to avoid duplicate data based on date so I declare date as unique but that simply causes multiple select for each individual row entry before INSERT query which couldn't be efficient on bulk processes. How we can deal with such problem. Suggestions are welcome. Thank you. -
Django how to pass an id of pagination and model id?
Thankyou i am getting a problem.I am using pagination in url passing a page id and want to pass my model driver id also. if a page is at 1 the url is *url(r'^rentacar/list/$', extension_views.rentacar_list),* but after user go to next page the url is: *url(r'^rentacar/list/(\d+)/$', extension_views.rentacar_list),* but i actually want to do is to reference driver id in the url that i am trying to pass. What am trying to do is to get driver id and page# in my url. how do i go about doing this? and how can i change my views and achieve it whereas its running through pagination Views.py @csrf_protect def rentacar_list(request, page_number=1): all_cars = Car.objects.all().order_by('-id') if menu_config.menu_item_rentacar_list_show_unavailable == 0: all_cars = all_cars.exclude(car_available=0) else: all_cars = all_cars cars_page = Paginator(all_cars, menu_config.menu_item_rentacar_list_pagination) args['cars'] = cars_page.page(page_number) template = Template.objects.get(template_default__exact=1) template_page = template.template_alias + str("/rentacar/rentacar_cars_list.html") return render(request, template_page, args) Urls.py url(r'^rentacar/list/$', extension_views.rentacar_list), url(r'^rentacar/list/(\d+)/$', extension_views.rentacar_list), but i want to achieve : url(r'^rentacar/list/driver/id/$', extension_views.rentacar_list), url(r'^rentacar/list/(\d+)/driver/id/$', extension_views.rentacar_list), -
Django collectstatics only collects admin static files
I have a django app running in docker containers with Nginx. All the static files (as css, js) for my app are being found successfully, with my nginx.conf file configured as it should be. But my django/admin static files are not being found. I have found this solution, and tried as it says: 1) Set both STATIC_URL and STATIC_ROOT in your settings.py 2) Define just a single static entry in your nginx conf (with trailing slashes). No need for a second one that addresses static/admin/: location /static/ { alias /path/to/static/; } 3) Use collectstatic which should collect admin -> static/admin. It will live under the same location as all the rest of your collected static media. python manage.py collectstatic When I do that, my STATIC_ROOT receives the admin static files, but is not receiving my app static files. I have no problem with docker volumes. NGINX container is receiving STATIC_ROOT content. But I will share my .yml file because maybe you detect an error on it. The "manage.py collectstatic" runs in my cldj/Dockerfile. My files: settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = ['/myapp/static/'] STATIC_ROOT = os.path.join(BASE_DIR, 'static_files') nginx.conf: location /static/ { autoindex off; alias /static_files/; } docker-compose.yml: version: '3' volumes: static_files: … -
How to define rating sheet model for an interview?
Pardon the bad drawing. Notations: I - Interview R1,R2,R3,R4 - Rounds RT - Rating Sheet A0, A1, A2, A4 - Aspect(Text Fields) under Rating sheet. Models: class Interview(models.Model): date = ............ class Round(models.Model): interview = models.ForeignKey(Interview) class RatingSheet(models.Model): name = ............ class Aspects(models.Model): sheet= models.ForeignKey(RatingSheet) I need a rating sheet to be filled for each interview. That sheet will hold ratings (1-10) for each aspect for each Round. What have I tried: I have thought of creating a form dynamically for an Interview with N rounds and accept ratings as drop down . And I collect all via request.POST. And create a dictionary like: rating_interview_1 = {'interview_pk': { 'Round1': {'ASP1': 5, 'ASP2':10}, 'Round2': {'ASP1': 5, 'ASP2':10}, 'Round3': {'ASP1': 5, 'ASP2':9}, } } And then save it to database somehow. I think this can be difficult to edit or maintain. Can I get some suggestions on the correct way to design this ?