Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Authenticating with Adwords Googleads without local storage
So having trouble finding documentation or tutorials on this. We're at the starts of a project using Python (Django) and are putting together a couple of proof-of-concept functions. I'm trying to use the googleads python library to authenticate with the adwords api. Currently though, I can only find examples that pull the adwords credentials from local storage: adwords.AdWordsClient.LoadFromStorage() The problem is, we'll be storing api keys and the likes in the database as multiple adwords managers may be utilizing the tool. As such, it's not ideal to store the credentials in a static file (it looks like the credentials for loadfromstorage are stored in a yaml file, though I'm having a bit of trouble finding details even on that). Does anyone have a good example of setting up an adwords client "on the fly", knowing the api key and generating other items as needed. Let me know y'alls thoughts. Thanks! -
Django does not display model data
I have a few uploaded files and I want to display their names in a template. That technically shouldn't be a problem, that should work with {% for obj in objs %} <li>{{obj.field}}</li> But in my case strangely it doesn't show anything. My files are uploaded and present in my database, but nothing shows. I have searched for a solution, but most similar problems had something to do with syntax mostly. My Document class: class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.document) And this is how I display them: <div class="card-body text-light"> {% for file in doc %} <b>{{file.description}}</b> {%endfor%} </div> I have looked in the documentation and a couple more tutorials and in theory it should be able to display the files. -
How can I add automatically CRUD permissions to a django model inside the Meta class?
Imagine I had the following model class Post(models.Model): name = models.CharField(max_length=20) body = models.TextField() class Meta: permissions = permission_generator() and what I want is that the permission_generator() to generate the tuple ( ('create_pet', 'create post'), ('read_pet', 'read post'), ('update_pet', 'update post'), ('delete_post', 'delete post'), ) In a way that I could reuse in all my models without repeating myself each time I define a new model. how can something like this be implemented? -
Django - iterate over checkbox model choice choices
Trying to figure out how to iterate over checkbox choices in Django template. model class DruhNehnutelnosti(models.Model): meno = models.CharField(max_length=255, ) typ = models.CharField(max_length=25, choices=settings.DOPYTY_NEHNUTELNOST_TYP_CHOICES, default='byt') where DOPYTY_NEHNUTELNOST_TYP_CHOICES=(('byt','Byt'),('ine','Iné)) I need to separate choices with different types to different divs. So, in form, all DruhNehnutelnosti checkbox choices with typ=='byt' will be in one div and rest in the other. I can do it by manually passing two separate lists of DruhNehnutelnosti objects but I think it should be able to do it using form. -
self.client.post not working in a test
I am having an issue getting this test to work. Here is the whole file on github https://github.com/cbaldwin20/project_9/blob/master/menu/tests.py. Thanks for any advice. Here is the test user = User.objects.get(id=1) def test_edit_item_view_post(self): self.client.post(reverse('mysite:item_edit', args=[self.item.id]), { 'name': 'Ketchup', 'description': 'Heinz brand', 'chef': user, 'ingredients': ['1'] }) item1 = Item.objects.get(id=1) self.assertEqual(item1.name, 'Ketchup') Here is the view I am testing def edit_item(request, pk): item = get_object_or_404(Item, pk=pk) if request.method == "POST": form = ItemForm(instance=item, data=request.POST) if form.is_valid(): form.save() return redirect('mysite:item_detail', pk=pk) form = ItemForm(instance=item) return render(request, 'menu/item_edit.html', {'form': form}) This is the form class ItemForm(forms.ModelForm): class Meta: model = Item exclude = ('created_date',) This is the model the form uses class Item(models.Model): name = models.CharField(max_length=200) description = models.TextField() chef = models.ForeignKey('auth.User') created_date = models.DateTimeField( default=timezone.now) standard = models.BooleanField(default=False) ingredients = models.ManyToManyField('Ingredient') -
Login Panel is Working offline in my Django project but when i add the same with https certificate on my shared hosting login panel isn't working
I have been stuck in serious issue and the thing goes this way. I am currently working a django project and its working absolutely fine when i run the same offline but a project cant be offline always so i bought a2hosting shared hosting server with ssl certificate and set up an virtual environment Now the problem is when the login panel is opened i.e staff login panel www.example.com/admin instead of logging me in or splashing a error messoge about wrong username or password its flashing or redirecting me to another page Error 404. How can i make this work fluently my url.py goes this way. from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ] -
django different product prices
I am trying to add different prices for the weight of the product and need to save the cost in the order regarding the weight selection by the user. class ProductPrice(models.Model): QUANITY = ( (1, '1'), (3, '3'), (5, '5'), ... ) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='prices') price = models.IntegerField(default=0) quanity = models.CharField(max_length=3, default=1, choices=QUANITY) In order models i override save metod: class ProductInOrder(models.Model): order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) nmb = models.IntegerField(default=1) price_per_item = models.IntegerField(default=0) total_price = models.DecimalField(max_digits=10, decimal_places=2, default=0) def save(self, *args, **kwargs): if self.nmb > 3: quanity = 1 self.price_per_item = self.product.prices.get(quanity=quanity).price elif self.nmb >= 5: quanity = 5 self.price_per_item = self.product.prices.get(quanity=quanity).price elif self.nmb >= 10: quanity = 10 self.price_per_item = self.product.prices.get(quanity=quanity).price elif self.nmb >= 20: quanity = 20 ... return super(ProductInOrder, self).save(*args, **kwargs) But this is not what i need.It is likely to trigger a DoesNotExist. How to implement it? -
How to customize password_reset_confirm.html
I put a file named password_reset_confirm.html in my Django project's templates/registration/ directory. But if I change the extends tag it won't load anything else. This template loads when a user clicks a password reset link from their email inbox. Here's what my password_reset_confirm.html looks like: {% extends "admin/base_site.html" %} {% load i18n %} {% block breadcrumbs %} <div class="breadcrumbs"> <a href="{% url 'admin:index' %}">{% trans 'Home' %}</a> &rsaquo; {% trans 'Password reset confirmation' %} </div> {% endblock %} {% block title %}{{ title }}{% endblock %} {% block content_title %}<h1>{{ title }}</h1>{% endblock %} {% block content %} THIS IS A CUSTOM FILE; I ONLY ADDED THIS SENTENCE. {% if validlink %} <p>{% trans "Please enter your new password twice so we can verify you typed it in correctly." %}</p> <form method="post">{% csrf_token %} {{ form.new_password1.errors }} <p class="aligned wide"><label for="id_new_password1">{% trans 'New password:' %}</label>{{ form.new_password1 }}</p> {{ form.new_password2.errors }} <p class="aligned wide"><label for="id_new_password2">{% trans 'Confirm password:' %}</label>{{ form.new_password2 }}</p> <p><input type="submit" value="{% trans 'Change my password' %}" /></p> </form> {% else %} <p>{% trans "The password reset link was invalid, possibly because it has already been used. Please request a new password reset." %}</p> {% endif %} {% endblock … -
How should I be using celery for my project in production?
Currently I am doing "celery -A myproj worker -l info" locally in my development environment to use celery. Though every time I see celery in a production environment I see people using celery with something like "celery multi start". What is the difference between these two and what should I be using to best scale my app in production? I own a video editing site and video processing tasks are done in the background. I will be using systemd to daemonize celery in production, setting celery up as a service. I am curious about what my ExecStart command should be. Thanks in advance -
How to display data in template
I have a question. How to display qr_data value in template. def qr_data(self, obj): return format_html( ''' ID: {}<br/> Size: {}<br/> Producer: {}<br/> Packed by: {}<br/> Packed date: {}<br/> <br/> ''', obj.id, obj.size, obj.producer, obj.tested_by, obj.test_date, ) -
How to write Facebook info on a puicture
I've created a website (on my local machine) using python (Django) but I want to write the user's info like birthday, name or city on a picture and use it like a troll quiz like: where are you going to live in 2020 and I The result would be a picture of the country or the city side by side with the user's profile picture and the name of the city.... Ex: enter image description here -
auto reverse relation Django
i have 2 models in django one "user" and another "relation between user" i want to know how to say django to automatically save the reverse relation when i made one between user, cause i have a template with a table who display the relation of a user. I want when a i made a relation for a user1 with a user2 the reverse relation are add automatically in the table of the user2. here my code: CIVILITE_CHOICE = ( ('Mr', 'Monsieur'), ('gérant', 'Mr le gérant'), ('gérante', 'Mme la gérante'), ('Mme', 'Madame'), ('Societe', 'Societe'), ('Autre', 'Autre'), ('', '') ) class Planteur(models.Model): pacage = models.CharField("Numéro pacage", max_length=9, primary_key=True, help_text="Un nombre de 9 chiffres") civilite = models.CharField( "Civilité", max_length=20, choices=CIVILITE_CHOICE, default='', blank=True) nom = models.CharField("Nom", max_length=200, help_text="200 caractères maximum.") prenom = models.CharField("Prénom", max_length=100, help_text="200 caractères maximum.") siret = models.CharField("SIRET", max_length=14, blank=True, help_text = "code Insee permettant l'identification d'un établissement ou d'une entreprise française.", null=True) LPG = models.CharField("Numéro LPG", max_length=100, blank=True, help_text = "Identifiant LPG du planteur.", null=True) contremarque = models.CharField("Contremarque", max_length=100, blank=True, null=True) denomination = models.TextField("Dénomination", help_text = "Texte d'aide", null=True, max_length=100, blank=True) gerant = models.TextField("Gérant", help_text = "Texte d'aide", null=True, blank=True) adresse = models.CharField("Adresse", help_text = "Adresse du planteur", max_length=255, null=True, … -
How to change ForeignKey value using inlineformset?
I have two models and forms linked by the ForeignKey 'squad'. In my templates I have the user first typing the Squad name and then the shooters. I am trying to hardcode the 'squad' field of my Shooters with the 'squad_name' of my ShooterSquad so the user doesn't have to type the squad name every time for every shooter. models.py class ShooterSquad(models.Model): squad_name = models.CharField(unique=True, max_length=100) school = models.CharField(max_length=100, null=False) def __str__(self): return self.squad_name class Shooter(models.Model): name = models.CharField(max_length=100) squad = models.ForeignKey(ShooterSquad, to_field='squad_name', related_name='squad', on_delete=models.PROTECT) def __str__(self): return self.name forms.py class ShooterSquadForm(forms.ModelForm): class Meta: model = ShooterSquad fields = ['squad_name', 'squad_total_score', ] class ShooterForm(forms.ModelForm): class Meta: model = Shooter fields = '__all__' class BaseShooterFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super(BaseShooterFormSet, self).__init__(*args, **kwargs) self.queryset = Shooter.objects.none() ShooterFormSet = inlineformset_factory( ShooterSquad, Shooter, form=ShooterForm, formset=BaseShooterFormSet, extra=1, max_num=3, exclude=('squad',) ) views.py def add_multiple_shooters(request): if request.method == 'POST': squad_form = ShooterSquadForm(request.POST) formset = ShooterFormSet(request.POST) if squad_form.is_valid() and formset.is_valid(): set_squad = squad_form.cleaned_data.get('squad_name') for f in formset.forms: f.cleaned_data['squad_id'] = set_squad f.cleaned_data['squad'] = set_squad print(formset.cleaned_data) squad_form.save() formset.save() return redirect('anasp:mainpage') else: print("ERROR") formset = ShooterFormSet() squad_form = ShooterSquadForm() context = { "title": title, "formset": formset, "squad_form": squad_form, } return render(request, "anasp/scores/shooter_formset.html", context) Input Form Sample My cleaned_data prints:[{'shooter_number': 67, 'squad': … -
render current status only on template in StreamingHttpResponse in Django
i was trying to display the status of processing to the user on the front end when i was using StreamingHttpResponse i was able to get the current status but the current status is being appended with the previous one i want the response template containing current yield only views.py from django.shortcuts import render from django.http import StreamingHttpResponse,HttpResponse import time def f1(): x = 0 while x<5: time.sleep(1) x = x+1 code = """<p>{}</p>""".format(x) yield code def home(request): return StreamingHttpResponse(f1()) output in browser <p>1</p> <p>2</p> <p>3</p> <p>4</p> expected output 1st second <p>1</p> 2nd second <p>2</p> 3rd second <p>3</p> 4th second <p>4</p> instead of appending the previous yield i want the template to be filled with the current yield -
Iterating through Django Rest API and obtaining an error
I have the following Django Rest API structure: [ { "title": "Project 1", "description": "API projects", "members": [ { "latest_activity": "15151020", "first_name": "AleX", "minutes_last_week": 0, "last_name": "Mol", "id": 23, "minutes_total": 30, "minutes_today": 0 }, { "latest_activity": "1515181664", "first_name": "Annie", "minutes_last_week": 0, "last_name": "Az", "id": 47, "minutes_total": 20, "minutes_today": 0 } ] }, { "title": "Project 2", "description": "Developer test (internal project", "members": [ { "latest_activity": "1511600", "first_name": "Ivan", "minutes_last_week": 0, "last_name": "XJJNX", "id": 18, "minutes_total": 10, "minutes_today": 0 }, { "latest_activity": "1516985", "first_name": "Lauren", "minutes_last_week": 0, "last_name": "Gom", "id": 39, "minutes_total": 560, "minutes_today": 0 } ] } ] What I want to do is iterate over this API, and obtain all the project names and developers that have been working in each project, so I developed the following function: def execute(): respuesta = requests.get('http://projd.herokuapp.com/api/v1/activities/?format=json', auth=('xxx','xxx')) upworkresponse = respuesta.json() encoded = json.dumps(upworkresponse) decoded = json.loads(encoded) for team in range(0, len(decoded)-1):decoded[team]["members"] print(team["first_name"]+" "+ team["last_name"] + " has been working in " + team["latest_activity"]) And I'm doing something wrong and I'm obtaining the following error: TypeError: 'int' object is not subscriptable. I can't understand why. -
'list' object has no attribute 'filter' on instance model filtering in django views
This error is driving me crazy: I am trying to loop through the keys of a dictionary to check if any of them is found in a list of years, so as to filter records by year in views.py, and I am getting this error. The instance model I apply the filter (e.g. past_runnings) is derived from chaining two models with different fields. The strange part is that the same check is executed without error with a list containing the type of sport. Any suggestions? Here's the code: p_runnings = runnings.filter(race_id__race_starts__lte=datetime.now(), participated=True) my_runnings = MyRace.objects.filter(runner_id=runner) past_runnings = list(chain(p_runnings, my_runnings)) # instance from chained models p_types = types #type of sport p_years = list(set(r.race_id.race_starts.year if isinstance(r, Running) else r.race_starts.year for r in past_runnings)) # no error for k, v in p_races_dict.iteritems(): if isinstance(v, dict): if k in p_types: p_runnings_filtered = past_runnings.filter(race_id__type=k).filter(type=k) p_races_dict[k]['p_races_num'] = p_runnings_type_filtered.count() # 'list' object has no attribute 'filter' error for k, v in p_races_dict.iteritems(): if isinstance(v, dict): if k in p_years: p_runnings_filtered = past_runnings.filter(race_id__race_starts__year=k) -
Why is my Django url redirecting to wrong url?
I have three django apps in a project by the name visit, main, and startup. In the a main base template I have a link on the navigation bar for redirecting user to index template in startup app. (note I have two urls by the name index but I am using namespacing). here is my main base.html: <li class="nav-item"> <a class="nav-link" href = '{% url 'startup:index'%}'>Startup</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Products</a> </li> <li class="nav-item"> <a class="nav-link" href="#">VCN</a> </li> The urls of the startup.urls looks like: from django.conf.urls import url from . import views app_name = 'startup' urlpatterns = [ url(r'^$', views.index, name = 'index'), ] Instead of redirecting me to this, the link is taking me to the index of the visit app (which also has the same url name but different name space). visit.urls: from django.conf.urls import url from . import views from django.contrib.auth import views as auth_views app_name = 'visit' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'login/$', auth_views.login, {'template_name': 'visit/registration/login.html'}, name='login'), # url(r'accounts/profile/', views.profile, name='profile'), # need to change the app directory from here url(r'^register/', views.registration, name='registration'), ] What M I doing wrong here? Is there another way to take user to another app through a link … -
Django & Js : use cleaned_data for simple input
i've created a form in forms.py , and after submiting the form, the values are inserted in my database smoothly, using form.cleaned_data. my template has a button (called : "ajouter une ligne") that adds a new line (the line contains a form similar to the original one). this action (of adding line) is coded by Js. my problem is ,when i want to submit the final form that contains the original line and the second . it only submits the first one, because the first ligne is created on forms.py so on submition it's submited with clean_data . However the second line is created on the template using js directly so form.cleaned_data doesn't work on it. Please any ideas , how can i use cleaned_data on my second line too? PS: when i replace form.cleaned_data with request.POST it adds both lines, but i want to add all my lines using cleaned_data because i read that for data security i need to work with form.cleaned_data. So please help me resolve this . Thank You So much -
Creating a proper way to store list of records bound to account
I'm planning to make a simple web app in Django (as a way to learn programming), but I have a hard time to find a way to store a list of items bound for certain account. For example, I've got a person that added a list of items of items such as milk, eggs, flour, water. You can delete those items, add new, and store different lists for every person. Firstly I was thinking about the database, but each item would need to be a column, and that wouldn't be flexible. What's the proper way to implement that? First time while learning to code it was really tough to even search for something. -
How to obtain database id from the struct_block.StructValue in the wagtail block template?
Building a custom template for the wagtail StreamField block I found myself in the situation that I need somehow pass the ID of the current block to the other views. For instance when the URL is clicked in the particular block, the landing page view must know exactly in which of the blocks the URL has been clicked. Then the view can extract other information which is associated with the particular block but not necessarily visually present to the user. My current strategy is using the snippets, so I can pass the ID of the snippet and the view may obtain related but beforehand hidden data. This works not so bad, but people have to edit the content in two places and I have to look at their sad faces. It seems that the value variable in the block template context is an instance of the wagtail.core.blocks.struct_block.StructValue, which gives me access to all the fields of the block but it doesn't seem to reveal its footprint in the DB. Further value has an interesting attribute: value.block, which seems like it's an instance of the actual model used to construct the block, but again I can't find anything useful like id … -
Django formset fails date validation with valid date
I'm running into a date validation error with use of a django formset. I do not get the same validation error when I formset.is_valid(). The problem I'm experiencing is that the form is_valid check fails, only with the view and template use (not in the shell) specifically when using a date in the form of "March 20 2018" whereas it always passes with "2018-03-20". Also I can verify the data is in the request.POST but the invalid due_date key is missing from self.cleaned_data when I look for it in the form's clean method. Perhaps that's normal given the invalid key but I would expect that to occur after the clean, not before, if at all. Feels like maybe its a django bug, I'm on django 2.0.2 Here's a summary of construction, its pretty vanilla: # models.py class Schedule(models.Model): # ... name = models.CharField(max_length=256) status = models.CharField(max_length=16, default=choices.NOT_STARTED, choices=choices.SCHEDULE_STATUSES) due_date = models.DateField(blank=True, null=True) # ... # forms.py class ScheduleForm(forms.ModelForm): class Meta: model = models.Schedule fields = ['name', 'user', 'status', 'due_date'] # views.py def line_schedules_edit(request, line_slug): line = get_object_or_404(models.Line, slug=line_slug) queryset = line.schedules.all() ScheduleFormSet = modelformset_factory(models.Schedule, form=forms.ScheduleForm) if request.method == 'POST': schedules_formset = ScheduleFormSet(request.POST) if schedules_formset.is_valid(): schedules_formset.save() return HttpResponseRedirect(reverse('products:line-schedules-edit', kwargs={'line_slug': line_slug})) else: … -
Docker Django can't find static files 404error
I would like to deploy my website in django to docker. Problem is, when i run docker-compose up, website html is loaded, but static content like css, js, logo, mp3 not. I think that this is because my url. On localhost my website runs correctly, but server has prefix something like http://127.0.0.1:8000/Something. I repaired urls so html files run but my static files in settings.py looks like this: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] and for example my homepage.html with js and css included (this works on localhost) like this: <head> <meta charset="UTF-8"> <title>Title</title> {% load static %} <link rel="stylesheet" href="{% static "styles/homepage.css" %}"> <script src="{% static "scripts/homepage.js" %}"></script> </head> but when server runs on http://127.0.0.1:8000/Something it show up this error in the command line: As you can see, the path must be not http://86.110.225.19/static/styles/homepage.css but http://86.110.225.19/SOMETHING/static/styles/homepage.css How can i fix this? Thank you so much. -
OpenCV python - show captured image in html
Is it posible to show captured image by OpenCV in html without saving it first to disk? I'm capturing a video from camera, frame by frame and I'm getting the numpy array. I was thinking that there should be an easy way to convert it to .jpg/.png/... and access it in html but so far I have not found a solution. -
How to combine migrations.RunPython and migrations.RunSQL in django migration operation
I am trying to write a migration which grants readonly permissions to each schema in my multi-tenant postgres DB. The migrations run once per schema, so what I would like to do would be capture the name of the schema for which it is running, and then use that schema_name in my SQL statement to grant permissions for that schema. In django, I can create a migration operation called 'RunPython', and from within that python code I can determine for which schema the migrations are currently running (schema_editor.connection.connection_name). What I want to do is pass that information to the next migration operation, namely "RunSQL", so that the SQL I run can be: "GRANT SELECT ON ALL TABLES IN SCHEMA {schema_name_from_python_code} TO readaccess;" If anyone can shed any light on this issue it would be greatly appreciated. Cheers! -
Django orm: how to query count on multiple manytomany
Given these models: class Bar(models.model): title = models.CharField(max_length=100) class Car(models.model): title = models.CharField(max_length=100) class Foo(models.model): title = models.CharField(max_length=100) bars = models.ManyToManyField(Bar, ) cars = models.ManyToManyField(Car, ) I need a list of foo annotated with bar count and car count: foo nb_bar nb_car ------------------- foo1 2 10 I tried with this (works fine): Foo.objects.annotate(nb_bar=Count('bars')).get(pk=1).nb_bar = 2 Foo.objects.annotate(nb_car=Count('cars')).get(pk=1).nb_car = 10 But with two annotations together the result is wrong: Foo.objects.annotate(nb_bar=Count('bars'),nb_car=Count('cars')).get(pk=1).nb_bar = 20 Foo.objects.annotate(nb_bar=Count('bars'),nb_boo=Count('cars')).get(pk=1).nb_car = 20 This probably corresponds in sql to two joins. In SQL, here after I got it works fine, but how to do it with django orm : select f.id, f.title, b.nb_bar, c.nb_car from foo f join ( select foo_id , count(*) nb_bar from foo_bar group by foo_id ) b on (f.id = b.film_id) join ( select foo_id , count(*) nb_car from foo_car group by foo_id ) c on (f.id = c.film_id) ; Could anyone help me please? Thank you very much in advance!