Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make an update function in django
i have an update function that allow user to update a form with pre-populated data using django the problem once the user try to enter to the update page the system display the below error : local variable 'form' referenced before assignment views.py def update(request,pk): instance = get_object_or_404(suspect,pk=pk) if request.method == "POST": form = suspectForm(request.POST or None,instance=instance) if form.is_valid(): instance = form.save(commit = false) instance.user = request.user instance.save() return redirect('result',pk = instance.pk) else: form = suspectForm(instance = instance) return render(request,'blog/update.html',{'form':form}) update.html {% extends "testbootstarp.html" %} {% load static %} {% block content %} <div class="offset-3 col-md-6"> <form method="post"> <div class="form-group">{% csrf_token %} {% for field in form %} <div class="field"> <label>{{field.label_tag}}</label> {{field}} {% for error in field.errors %} <p class="help is-danger">{{error}}</p> {% endfor %} </div> {% endfor %} </div> <button type="submit">edit</button> </form> </div> {% endblock content %} -
How To Fix Miscased Procfile in Heroku
Heroku will not reload my corrected Procfile I have ran git status which shows me the Procfile and I realized that I spelled Procfile with a lower case p. I saw the error and updated the file name in my project but when I saved and ran git status again it stills shows it lower case. Of course now its not showing the site on Heroku. Changes not staged for commit: (use "git add ..." to update what will be committed) (use "git checkout -- ..." to discard changes in working directory) modified: procfile remote: -----> Discovering process types remote: remote: ~ Mis-cased procfile detected; ignoring. remote: ~ Rename it to Procfile to have it honored. remote: remote: Procfile declares types -> (none) Total newbie on my first project. Should I delete the project on Heroku and just start all over fresh or can I just do a git init and then just push everything up again to Heroku? -
Autocomplete with ajax and jquery does not work with Bootstrap styling
I try to implement a simple jquery autocomplete widget with an input form on the main page but it does not work. I work in Django 2.2. When I try to put the autocomplete widget on the main page it is not working. Ajax queryset is not getting generated. When I put the same code on a blank page without any styling, it works fine. So, when I put the same widget on the main page(with Bootstrap styling) but connecting to a predetermined (hard coded) queryset, it works. In blog/base.html file: <!-- 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 'blog/main.css' %}"> <!-- for Autocomplete --> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.12.4.js"></script> <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <!-- Input --> <div class="ui-widget"> <label for="search"> Search </label> <input id="search" placeholder="Search by ticker"> </div> <script type="text/javascript"> $(document).(function() { $("#search").autocomplete({ source: "{% url 'ajax_load_project' %}", minLength: 1, }); }); </script> <!-- 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> views.py def ajax_load_project(request): if request.is_ajax(): q = request.GET.get('term', '') projects = Project.objects.filter(title__istartswith=q)[:7] results = [] for project in projects: project_json = {} project_json['id'] = project.pk project_json['value'] = … -
Can log in from django shell but cannot log from views
Having the exact same problem as in Python logging works in shell, but not in views settings:py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'myapp_error.log', }, }, 'loggers': { '': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } views.py import logging logger = logging.getLogger(__name__) logger.warning('Hi this is the warning logger working') -
How to assign Group permissions to individual records in Django
I have a model in which I would like to assign specific records to a user group (or several user groups), so that an individual record is editable/viewable only by members of those groups associated with it. I want the user who creates a record in the model to be able to assign the group permissions for that record. What's the best way to do this? E.g. can I assign a OneToMany field? Something like: from django.contrib.auth.models import Group, Permission class MyModel(models.Model): title = models.CharField(max_length=200, null=True) groups = [ What comes next? ] -
problems registering using user extend
I created a system where I have the user that is the default of django and I created the Model Fotografos, which extends the User. The problem is that it does not save, it always returns to the form. I already tried to take some fields. I think the error occurs after these two lines form = PhotographersForm (request.POST) if form.is_valid (): after them nothing else happens. model.py class Photographers(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=False) lastname = models.CharField(max_length=50, blank=False) email = models.EmailField(blank=False) phone = models.CharField(max_length=20, blank=False) cpf = models.CharField(max_length=19, blank=False) cnpj = models.CharField(max_length=19, blank=False) birthday = models.CharField(max_length=10, blank=False) address = models.CharField(max_length=50, blank=False) number = models.CharField(max_length=10, blank=False) district = models.CharField(max_length=30, blank=False) zip_code = models.CharField(max_length=25, blank=False) city = models.CharField(max_length=30, blank=False) state = models.CharField(default='RS', max_length=50, choices=STATE_CHOICES, blank=False) password1 = models.CharField(max_length=15, blank=False) def __unicode__(self): return self.name @receiver(post_save, sender=User) def new_register(sender, instance, created, **kwargs): if created: Photographers.objects.create(user=instance) instance.photographers.save() views.py def register(request): usuario = Photographers.objects.all() form = PhotographersForm() data = {'usuario': usuario, 'form': form} return render(request, 'paneladmin/register.html', data) def new_register(request): if request.method == 'POST': form = PhotographersForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.is_staff = True user = form.save() user.refresh_from_db() user.photographers.name = form.cleaned_data.get('name') user.photographers.lastname = form.cleaned_data.get('lastname') user.photographers.email = form.cleaned_data.get('email') #user.photographers.picture = … -
Getting "App crashed" error after deploying Django app on Heroku
I am getting these following two errors after deploying my Django application on Heroku: 2019-07-21T22:09:21.799421+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=myapp.herokuapp.com request_id=aa4c90d2-f8de-4244-abf8-1cfdde758a7f fwd="188.253.234.137" dyno= connect= service= status=503 bytes= protocol=https 2019-07-21T22:09:22.317447+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=myapp.herokuapp.com request_id=fbe1e39e-5f98-4439-8031-848937843144 fwd="188.253.234.137" dyno= connect= service= status=503 bytes= protocol=https -
Django doesn't log the user in
I have a login function, however when I try to login with a user that is not admin Django's authenticate function returns None even though the user exists in the database and the function receives the right username and password. def login_user(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] print(username, password) user = authenticate(username=username, password=password) print(user) if user is not None: login(request, user) return redirect("/") else: return render(request, "orders/login.html", {"message":"Username and password did not match."}) else: return render(request, "orders/login.html") -
Most performant way to integrate a crawler inside flask page
I've made a simple crawler that use multiprocessing.dummy.Pool to create a ThreadPool to open a bunch of urls together and check for links then open them to search for a specific word then return a list of links containing that word if any were found. The thing is, when i run it directly from terminal .. it runs very fast. But when i run it from Flask page as an external script with subprocess.call(["python", "myscript.py", "urls_file.txt", "word_to_search_for"]) it runs very slow and hangs unlike the first one. In flask, the data is submitted via POST as a form. Please, i would like to know what is the best way for apps like that. Thanks. -
How do I aggregate values in a python list or dictionary based on book title?
Currently, my data is like this or a dictionary, not aggregated by title: {Great Expectations, Bookstore 1, $8.99}, {Great Expectations, Bookstore 2, $12.99}, {Great Expectations, Bookstore 3, $6.99}, {Tales from the Crypt, Bookstore 1, $5.99}, {The Sisterhood of the Traveling Pants, Bookstore 3, $8.99} {Oprah: The Icon, Bookstore 2, $6.99} {Oprah: The Icon, Bookstore 3, $9.99} I'd like to create list of a dictionary of prices that's aggregated by title that looks like this: [Great Expectations, {price1: $6.99, price2: $8.99, price3: $12.99}], [Tales from the Crypt, {price1: $5.99}], [The Sisterhood of the.., {price1: $6.99}], [Oprah: The Icon, {price1: $6.99, price2: $9.99}] Thanks for your help. I will eventually pass this data into a Django view as a list. If you could help that would be great. There can be more than 3 prices, n prices. -
How to create a video blog with Django?
I am learning Django. I have started with Django girls blog tutorial which is very basic. Now I want to convert this with the conceptual video blog where user can upload a video like Youtube and user will be able to play on my blog; and some description will be there. Besides, I want every post will be moderated by admin. Can anyone expert help me with some coding suggestion as I am newcomer. Thanks in advance! I have Already complete the Django girls blog tutorial and now moving for advance opting that it has offered for expanding the blog. So I will be very thankful to the solution provider. This is my assignment but I can't find any solution on my own. I hope some expert might have some time to provide me a solution. Thank you very much! -
GeoDjango: Finding objects in radius
I'm currently trying to get a list of points contained within a radius but I can't get it working. Here is the code of my view so far: from django.contrib.gis.geos import Point from django.contrib.gis.measure import Distance class AreaInfoViewSet(viewsets.ViewSet): queryset = models.AreaInfoRequest.objects.all() serializer_class = serializers.AreaInfoRequestRequestSerializer def list(self, request): center_point = 'POINT(48.80033 2.49175)' radius = "50.0" data = {"center_point": center_point, "radius": radius, "source_ip": utils.get_client_ip(request)} serializer = serializers.AreaInfoRequestRequestSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() # Contains an object with field "from_location"="SRID=4326;POINT (2.49157 48.80029)" objs = models.PointsResult.objects.all() float_radius = serializer.data["radius"] center_point = serializer.data["center_point"] # Point object res = models.PointsResult.objects.filter(from_location__distance_lte=( center_point, Distance({"meter": float_radius}))) # Here the res doesn't contain the unique object in the db even if it's within the radius return Response(res) Any idea why it's not working? Thank you -
How can i validate a field in a model class with another field in a separate model class in django
I'm working with django_rest_framework and i'm supposed to great an application where a Group exists with a group admin who will set some parameters for other groupmembers to use as their acceptance criteria. I have two models instances, Group and Groupmembers, Groupmembers has a foreignKey relationship to Group. Inside the Group, i have a field that holds a minimum value(number=money) a Groupmember can deposit. Please, how can i 1. Ensure that when a groupmembers selects anything less than what was specified by the group admin while creating the group, an error is raised 2)Calculate the total amount deposited by a user for a given duration from this field in the GroupMember deposit = models.PositiveIntegerField() This is a custom validation i made to ensure the group admin is restricted to a minimum value and a maximum value from django.db import models class IntergerRangeField(models.IntegerField): def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs): self.min_value, self.max_value = min_value, max_value models.IntegerField.__init__(self, verbose_name, name, **kwargs) def formfield(self, **kwargs): defaults = {"min_value": self.min_value, "max_value": self.max_value} defaults.update(**kwargs) return super(IntergerRangeField, self).formfield(**defaults) Here's my model from django.db import models from django.shortcuts import reverse from django.contrib.auth.models import User # importing fixed amount file from .import fixed_amount class Group(models.Model): name = models.CharField(max_length=100) description … -
Cannot change column 'id': used in a foreign key constraint of table error on Django
Im trying to create models taking a MySQL database as reference using Django, but when I try to migrate it throws me the next error: Cannot change column 'id': used in a foreign key constraint 'fk_post' of table 'demoniosmv.images'" My models looks like this: from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Images(models.Model): #id = models.IntegerField(primary_key=True) fk_post = models.ForeignKey('Post', related_name="images", blank=True, null=True, on_delete = models.CASCADE) img_url = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = True class Post(models.Model): #id = models.IntegerField(primary_key=True) author = models.ForeignKey(User, related_name="posts", on_delete = models.CASCADE) title = models.CharField(max_length=200, blank=True, null=True) text = models.TextField(blank=True, null=True) created_date = models.DateTimeField(default = timezone.now) class Meta: managed = True And the SQL script from which I'm creating the database is this: -- MySQL Script generated by MySQL Workbench -- Sun Jul 21 14:14:44 2019 -- Model: New Model Version: 1.0 -- MySQL Workbench Forward Engineering SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'; -- ----------------------------------------------------- -- Schema demoniosmv -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema demoniosmv -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `demoniosmv` DEFAULT CHARACTER SET utf8 ; USE `demoniosmv` ; -- ----------------------------------------------------- -- Table `demoniosmv`.`post` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `demoniosmv`.`post` ( `id` INT … -
Calling script from Django on a webserver
I made a website and I deployed it with Nginx and Gunicorn on an Ubuntu server (18.04). In my site I call with subprocess some python scripts that are in my project folder. If I start them on terminal they work as well, but with subprocess they don't work. This problem also belongs to commands on terminal. @staff_member_required() def get_all_process(request): process = subprocess.Popen(["ps a"], shell=True, executable='/bin/bash', stdout=subprocess.PIPE) # /bin/bash -c output = process.stdout.readline().decode("utf-8") out = (process.communicate()[0]).decode("utf-8") return HttpResponse('{}, {}'.format(output, out)) @staff_member_required() def start_script(request): process = subprocess.Popen(["nohup /home/user/project/source/test.py >/dev/null 2>&1 &"], shell=True, executable='/bin/bash', stdout=subprocess.PIPE) # /bin/bash -c output = process.stdout.readline().decode("utf-8") out = (process.communicate()[0]).decode("utf-8") pid = process.pid + 1 return HttpResponse('{}, {}'.format(output, out)) How can I solve? -
How do I pass url path argument to view success url, in url patterns?
I want to pass the <int:pk> of my view_submission path to the success_url. Can you please help? I can't seem to find a way to do this here, without changing the code in my views file, which I'd really not like to do because I want to keep these all in the urls file. urlpatterns = [ path('', login_required(SubmissionsList.as_view()), name='all_submissions'), path('create', login_required(SubmissionCreate.as_view( success_url=reverse_lazy('all_submissions'))), name='create_submission'), path('view/<int:pk>', login_required(SubmissionDetail.as_view()), name='view_submission'), path('edit/<int:pk>', login_required(SubmissionUpdate.as_view( success_url=reverse_lazy('view_submission', kwargs={'pk': pk}))), name='edit_submission'), path('delete/<int:pk>', login_required(SubmissionDelete.as_view( success_url=reverse_lazy('all_submissions'))), name='delete_submission'), ] Thanks! -
django-simple-history Sum of columns for each historical snapshot
I've been trying to get the sum of one colum in my database. I know how to do it but when it comes to using django-simple-history and get the value for each snapshot (24 hours), I can't. It just returns the value for all snapshots together. How would I construct the correct ORM to get the individual value of each snapshot, so that I can use it inside my template to create a time graph with a for loop, that grabs each single snapshot in the db and the Node_Cores sum for that snapshot? Example of what i'm looking for: 17/07/19 - Sum = 190302 18/07/19 - Sum = 190583 19/07/19 - Sum = 190703 Views.py def networkOverview(request): GolemDatadb2 = GolemData.history.aggregate(Sum('Node_Cores')) print(GolemDatadb2) return render(request, 'golemstats/networkOverview.html', { 'GolemData':GolemDatadb2, }) Template: <script> var timeFormat = 'DD-MM-YYYY'; var config2 = { type: 'line', data: { datasets: [{ label: "Lorem", data: [{%for h in GolemData %} { x: "{{ h.history_date|date:" d / m / Y " }}", y: {{ h.Node_Cores}} }, {% endfor %}], fill: false, borderColor: 'red' }, ] }, options: { responsive: true, title: { display: false, text: "Core count by day" }, legend: { display: false }, scales: { xAxes: [{ … -
Is there a way to use an active Bootstrap element as an input to a Django form?
I want to use a Bootstrap list group as seen here as a choice selection tool in a form. One of the list items in the said Bootstrap list can have an active attribute at a time. I was hoping to map that active attribute to a choice in a Django forms.ChoiceField, thus making the list into a radio button of sorts. -
Django App not compatible with buildpack: App not compatible with buildpack: https://.../python.tgz
I want to deploy my django application on Heroku. But it seems impossible. after git push heroku master it says: Counting objects: 99, done. Delta compression using up to 4 threads. Compressing objects: 100% (97/97), done. Writing objects: 100% (99/99), 2.51 MiB | 98.00 KiB/s, done. Total 99 (delta 22), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to mammadovs. remote: To https://git.heroku.com/mammadovs.git Although, I didn't forget declaring heroku buildpacks:set heroku/python -
How to change data in database by clicking a button in HTML with Django
I have a mini project with Django. I have just a model with a counter total : class Reponse(models.Model): total = models.IntegerField() I have this view: def questions(request): _reponse = get_object_or_404(Reponse, id= 1) return render(request, 'vautmieux/test.html', {'reponse': _reponse}) And my HTML test display the variable total: <p id="block1"> {{reponse.total}} </p> My question is : I would like when I click on a button in the HTML, the variable total increases by 1. How can I do that ? With a form POST or GET ? May be there is a better method ? -
Why I'm receiving this an error TemplateDoesNotExist?
I'm receiveng this an error and I can't figure out why: TemplateDoesNotExist at /products/ products/product_list.html My code: #from django.views import ListView from django.views.generic import ListView from django.shortcuts import render # Create your views here. from .models import Product class ProductListView(ListView): queryset = Product.objects.all() tempalate_name = "products/list.html" def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_data(*args, **kwargs) print(context) return def product_list_view(request): queryset = Product.objects.all() context = { 'qs': queryset } return render(request, "products/list.html", context) As you can see, I have nowhere mentioned a path: products/product_list.html, I'm using products/list.html. How can I troubleshoot this issue? -
How to change QS structure in Django?
Currently, my QS is like this: Great Expectations Bookstore 1 $8.99 Great Expectations Bookstore 2 $12.99 Great Expectations Bookstore 3 $6.99 Tales from the Crypt Bookstore 1 $5.99 The Sisterhood of the Traveling Pants Bookstore 3 $8.99 Oprah: The Icon Bookstore 2 $6.99 Oprah: The Icon Bookstore 3 $9.99 I'd like to create a QS or just a dictionary that I could pass to my view that looks like this: Great Expectations, 3, {price1: $6.99, price2: $8.99, price3: $12.99} Tales from the Crypt, 1, {price1: $5.99} The Sisterhood of the.., 1, {price1: $6.99} Oprah: The Icon, 2, {price1: $6.99, price2: $9.99} Basically I don't care about the bookstore that it's sold at and want to compress the QS into just book titles with a dictionary or tuple of prices. It would be preferable if I could order those prices from min to max in the dictionary. -
Django Tests Against a Read Only Database
I'm looking for some best-practice advice on how to go about writing tests in this specific scenario I have. I've got a Django API that runs against a postgres database (which I have control over on my server) as well as a remote read-only MySQL database. The read-only db is provided by an external service, and they do provide a pretty liberal API for writing data to their database (so we overwrite our .save method to write to the API, rather than using the database directly), but this is all production data, so not something I want to mess with for tests. Do people have thoughts on how to organize this project so that it sets up a similar MySQL database, or just continuously mocks every write (in a way that writing API endpoint integration tests are still do-able). Happy to provide more details if needed. -
Is there any way i can render template and at the same time use django restful framework together
Is there any way i can render template and at the same time use django restful framework because i want to render template and give restful api at the same time in django using function views -
Why doesn't the first ModelFormSet pick up the id from request.POST?
I'm trying to add multiple of a ModelForm using the ModelFormSetFactory. Upon submission the first of the set returns an error saying "(Hidden field id) This field is required." even though the hidden id field is in the form. For any further forms in this set, this error does not occur and the id can be found in the cleaned_data. The view for this form (in views.py): class NewRecipeView(generic.TemplateView): def get(self, request, *args, **kwargs): ingredient_data = { 'ingredient-TOTAL_FORMS': '0', 'ingredient-INITIAL_FORMS': '1', } context = {"new_page": "active", "form": RecipeForm(), "formset_ingredient": RecIngFormSet(ingredient_data, prefix="ingredient"), } return render(request, 'recipes/new_recipe.html', context) def post(self, request): form = RecipeForm(request.POST) formset_ingredient = RecIngFormSet(request.POST, prefix="ingredient") print(request.POST) for fs in formset_ingredient: print(fs) print(fs.cleaned_data) if form.is_valid() and formset_ingredient.is_valid(): new_rec = form.save(commit=False) new_rec.created_at = timezone.now() new_rec.save() for fs in formset_ingredient: new_rec_ing = fs.save(commit=False) new_rec_ing.recipe = new_rec new_rec_ing.save() return HttpResponseRedirect(reverse('recipes:recipe', args=(new_rec.id,))) else: print('handle invalid forms here') And the actual form in forms.py: class RecipeIngredientForm(forms.ModelForm): class Meta: model = RecipeIngredient fields = ['quantity', 'unit', 'ingredient'] recIngFormSet = modelformset_factory(RecipeIngredient, RecipeIngredientForm) In the HTML I am building the form from {{ formset_ingredient.empty_form }} with javascript and making sure that I follow the rules set in {{ formset_ingredient.management_form }}. I think this bit is fine as the …