Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: 'editorial' is not a registered namespace
I'm getting the error of 'editorial' is not a registered namespace I've found this similar question: Django - is not a registered namespace But I'm currently using it's solution (to use a namespace in the project url file) and still getting the error. Proyect urls.py: """el_comercio_app URL Configuration""" from django.contrib import admin from django.urls import path, include urlpatterns = [ path("", include("editorial.urls", namespace='editorial')), ] editorial urls.py: from django.urls import path from editorial import views from django.contrib import admin app_name = 'editorial' urlpatterns = [ path('admin', admin.site.urls), path("", views.today_editorial, name="today_editorial") ] The error happens when running a test: coverage run manage.py test editorial -v 2 # models test class EditorialTest(TestCase): def create_editorial(self, title="only a test", body="yes, this is only a test"): return Editorial.objects.create(title=title, body=body, url="https://www.google.com", image = "https://img.elcomercio.pe/files/article_content_ec_fotos/uploads/2019/06/19/5d0ae893b3287.jpeg", date=timezone.now()) def test_today_editorial_view(self): url = reverse("editorial:today_editorial") resp = self.client.get(url) self.assertEqual(resp.status_code, 200) -
Google App Engine Standard can not find/execute Gunicorn
I have a project with a Django backend and an Angular frontend. I've deployed them as two services into Google App Engine Standard and the deploy is successful. However, when I try to access the backend url this-backend.appspot.com, i get /bin/sh: 1: exec: gunicorn: not found I have gunicorn in my requirements file: gunicorn==19.9.0 I also have defined the entrypoint: runtime: python37 service: default entrypoint: gunicorn -b :$PORT thisapp.wsgi handlers: - url: /static static_dir: static - url: /.* secure: always redirect_http_response_code: 301 script: auto But still get the same error. I looked into all the same issues on the Stackoverflow, and they were either because of the requirements or the entrypoint which I've defined both of them. Even when I go to the Stackdriver I can see the gunicorn folders inside the app engine:/: gunicorn gunicorn-19.9.0.dist-info This is the backend cloudbuild.yaml file: steps: - name: 'python:3.7' entrypoint: python3 args: ['-m', 'pip', 'install', '-t', '.', '-r', 'requirements.txt'] - name: 'python:3.7' entrypoint: python3 args: ['./manage.py', 'collectstatic', '--noinput'] - name: 'gcr.io/cloud-builders/gcloud' args: ['app', 'deploy', '--version=prod'] I'd really appreciate it if anyone has any solutions or recommendations as I've looked into almost all the same issues on the Internet. Thanks, James -
how get pk in get_absolute_url recursively
By using inlineformset I've created a createview, all is working very well but, I need to redirect the user to the created author detail view. How can I get the author id using the get_absolute_url in the model Book? I will explain in the following code what I've made. Firstly, I have two models with a relationship, Author and Book. class Author(models.Model): description = models.CharField("Description", max_length=150) author = models.ForeignKey( "Book", verbose_name=_("Book"), on_delete=models.PROTECT ) class Meta: verbose_name = _("Author") verbose_name_plural = _("Authors") class Book(models.Model): name = models.CharField("Book Name", max_length=150) class Meta: verbose_name = _("Book") verbose_name_plural = _("Books") def get_absolute_url(self): return reverse('author-detail', args=(need author pk here,)) Here, I have the formset. AuthorFormSet = forms.inlineformset_factory( Book, Author, form=AuthorForm, fields = ['description'], extra=2 ) And here I have my view. class BookAuthorCreateView(CreateView): model = Book fields = ['name'] template_name = "core/formset.html" def get_context_data(self, **kwargs): data = super( BookAuthorCreateView, self).get_context_data(**kwargs ) if self.request.POST: data['formset'] = AuthorFormSet(self.request.POST) else: data['formset'] = AuthorFormSet() return data def form_valid(self, form, *args): context = self.get_context_data() authors = context['formset'] with transaction.atomic(): self.object = form.save() if authors.is_valid(): authors.instance = self.object authors.save() return super(BookAuthorCreateView, self).form_valid(form) Thanks for your time. -
How to get all data from a loop using a django form?
I created a table from a loop. And in my table I make editions. And after editing the data, I will want to retrieve all the data in a dictionary. Here is my tablemplate: <form action="{% url 'Note_Update' %}" name="get_note" id="get_note" method="get"> <table border="1" class="stripe row-border order-column" style="width:100%"> <tr> <th>user</th> <th>point</th> </tr> <tbody id="table"> {% for a in team %} <tr scope="row"> <td class="text-center col-md-1">{{ a.user }}</td> <td class="text-center col-md-1">{{ a.point }}</td> </tr> {% endfor %} </tbody> </table> </form> here is my view or function: def Note_Update(request): get_note = request.GET.get('get_note') print(get_note) # get dictionary # example # {"A": "12" , "B": "18" , "C": "15"} return redirect('home') -
'NoneType' object has no attribute '__getitem__' Django , i got stuck when try to follow a tutorial
hello everyone im a student from indonesia, im following a video tutorial on how to make a website spesifically about digital marketplace, so theres a part when i try to make 'a auto generated thumbnail' feature, from high resolution picture that we upload, but the end i got this kind of error, that made me stuck to do my Project firstly im using django version 1.8.6, and python ver 2.7.10 heres my models.py from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import pre_save, post_save #signal from django.utils.text import slugify #signal from django.core.files.storage import FileSystemStorage def download_media_location(instance, filename): return "%s/%s" %(instance.slug,filename) class Produk(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) managers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="managers_produk", blank=True) media = models.ImageField( blank=True, null=True, upload_to=download_media_location, storage=FileSystemStorage(location=settings.PROTECTED_ROOT)#memindahkan dr media ke protected ) judul = models.CharField(max_length=30) slug = models.SlugField(blank=True, unique=True) deskripsi = models.TextField() harga = models.DecimalField(max_digits=100, decimal_places=2, default=1000.0) harga_sale = models.DecimalField(max_digits=100, decimal_places=2, default=1000.0, null=True, blank=True) #bisa di kosongin def __unicode__(self):#menampilkan list di admin berdasarkan judul return self.judul def get_absolute_url(self):#absolute url redirect success url ke slug path view_name = "produk:detail_slug" return reverse(view_name, kwargs={"slug":self.slug}) def get_download(self): view_name = "produk:download_slug" url = reverse(view_name, kwargs={"slug":self.slug}) return url def create_slug(instance, new_slug=None): slug = slugify(instance.judul) if new_slug is not None: slug=new_slug … -
Django urlpatterns - NoReverseMatch at... Reverse for '' with no arguments not found
I am building a modal form in Django that would allow the user to edit the details of an existing record. Specifically, in the paper_detail.html, there is a button that the user can click on, which would then load the specific paper in a modal form via ajax. Once the paper is loaded into the modal form, the user can edit it. When I go to http://127.0.0.1:8000/paper/796134/, I ran into the following error: NoReverseMatch at /paper/796134/ Reverse for 'edit_paper' with no arguments not found. 1 pattern(s) tried: ['search/edit/(?P<pk>\\d+)/$'] This is very puzzling to me because I expect it to go to paper_detail. urls.py: urlpatterns = [ path('paper/<int:pk>/', views.paper_detail, name='paper_detail'), url('', views.load_paper, name='load_paper'), url(r'^edit/(?P<pk>\d+)/$', views.edit_paper, name='edit_paper'), path('', views.HomePageView.as_view(), name='home'), ] What I found is that if I remove the (?P<pk>\d+) from the edit_paper pattern, the page loads fine. (i.e. http://127.0.0.1:8000/paper/796134/ loads correctly if url(r'^edit/(?P<pk>\d+)/$', views.edit_paper, name='edit_paper'), becomes url(r'^edit/$', views.edit_paper, name='edit_paper'), This would be problem solved but I believe I actually need to have (?P<pk>\d+) in the edit_paper pattern. This is because I need to pass the pk of the paper back to the edit_paper function by including {{object.pk}} as a parameter in form action. Please advise what is the best course … -
Django call_command before loading fixtures in tests
Is it possible to call_command() before loading the fixtures in TestCase? This code doesn't work - fixtures can't be loaded because the groups do not exist yet. class UserAPITestCase(APITestCase): fixtures = [ 'user/fixtures/user.json', ] def _fixture_setup(self): call_command('create_groups') super()._fixture_setup() -
Python - Django OperationalError no such table even though --run-syncdb
I cannot create new table (the 4th one called Vote) in my models. I have tried every solutions under: Django: OperationalError No Such Table including the --run-syncdb option during my migration execution. My migration process is: python manage.py makemigrations eathere python manage.py migrate --run-syncdb py manage.py runserver It executes successfully, however the table is not created. I check it by these commands: from django.db import connection tables = connection.introspection.table_names() seen_models = connection.introspection.installed_models(tables) And when I try to refer it on the admin site (after successfull registration of the model), it throws OperationalError No Such Table eathere_vote Could you please help me what could be the cause of the issue? My code is: from django.contrib.auth.models import AbstractUser, Group from django.db import models class CustomUser(AbstractUser): def full_name(self): return self.first_name + self.last_name class FoodProvider(models.Model): id = models.CharField(max_length=200, primary_key=True) description = models.CharField(max_length=200, default=None, blank=True, null=True) def __str__(self): return str(self.id) + " (" + str(self.description) + ")" class EatingOpportunity(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) food_provider = models.ForeignKey(FoodProvider, on_delete=models.CASCADE) class Meta: managed = False unique_together = (('group', 'food_provider'),) class Vote(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) food_provider = models.ForeignKey(FoodProvider, on_delete=models.CASCADE) vote_date = models.DateTimeField('vote date') class Meta: managed = False unique_together = (('user', 'group', 'food_provider', 'vote_date'),) … -
Associate database with an user using "uuid"
I have a desktop app which adds data to a database when user does the ctrl +c , ctrl +alt+c combination and it sends e-mails about the data to the user every x time. What I wanna do is build a django app, connect it to the same database with the desktop app. The scenario I want to built ;user gives an e-mail address to the web app , the web app gives an uuid to the user then starts the download of the desktop app, the user types that uuid on the desktop app,the desktop app connects to the database on cloud , user adds data to the database on the cloud using the desktop app. E-mail sender sends datas to the e-mail addresses using the database every x time . -
Efficiently retrieve from and add to ManyToManyField
I have two models, let's say Container and Item. Container has a ManyToMany field to associate Containers to Items. I want to add an Item to a Container and then list all of the Items in this container. However, I've noticed that Django queries for each item before it adds it, therefore I end up with three queries, one to get all of the Items, one to check if the Item I want to add is there, and another to add the Item. Is there a way to eliminate this superfluous checking? I've tried replacing the item_set entirely using the set command but it still adds the extra check for duplicates. # Select all items in item_set existing = container.item_set.all() # Select item in item_set (even though we know) and insert item into set container.item_set.add(new_item) In brief: I would like to end up with a new item added to the set and all the old items from the set in two queries -
Django client-side form validation of regexvalidator doesn't work
I have implemented Django model+form that I would like to validate on client side. Every constraint is validated perfectly as expected apart from a RegexValidator. The regex itself works fine in Python and JS alike. I believe the problem is that the validation does not propagate from Django's model/form to the front layer. I.e. the validation of regex on client's side does not even start. I have found a lot of similar questions here but none of the answers helps. For example here people advice using EmailValidator (can't since its not an email or any other specialized field), using parsley (I already use django-angular that would probably colide), or validate in HTML (I would really like to keep the DRY principle). Writing my own validator or naming parameters don't help either. Is there any way how to validate RegexValidator on client's side without third-party libraries? # models.py class Contact(models.Model): firstname = models.CharField(max_length=254) lastname = models.CharField(max_length=254) address = models.CharField(max_length=254) email = models.EmailField(max_length=254) phone_regex = RegexValidator(regex=r'^\+\d{8,15}$', message="Phone number must be entered in the format: '+99999999'. Up to 15 digits allowed.") phone = models.CharField(max_length=16, validators=[phone_regex]) # forms.py class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ('firstname', 'lastname', 'address', 'email', 'phone') # views.py … -
When published django-cms plugin from edit mode html template doesn't render model objects. But content reappears when switched to edit mode
Actually, I am new to Django-cms world. I tried almost every duplicate of this same question but none of them worked. I have created my custom plugin with just one ManyToManyField(). I went through Django-docs For many-to-many or foreign key relations to other objects but that didn't helped. Maybe I am lost somewhere, I would really appreciate any help. Thank you. Try1 PluginModel : class PortfolioPluginModel(CMSPlugin): portfolio = models.ManyToManyField(Portfolio) Try2 PluginModel : class PortfolioPluginModel(CMSPlugin): portfolio = models.ManyToManyField(Portfolio) def copy_relations(self, oldinstance): for p in oldinstance.portfolio.all(): p.pk = None p.plugin = self p.save() Try3 PluginModel : class PortfolioPluginModel(CMSPlugin): portfolio = models.ManyToManyField(Portfolio) def copy_relations(self, oldinstance): self.portfolios = oldinstance.portfolios.all() Apps Model: class Portfolio(models.Model): author = models.CharField(max_length = 100) description = models.TextField() image = models.ImageField(upload_to ='portfolioImage',blank = True, null = True) published_at = models.DateTimeField(auto_now_add = True) cms_plugins.py @plugin_pool.register_plugin # register the plugin class PortfolioPluginPublisher(CMSPluginBase): model = PortfolioPluginModel # model where plugin data are saved # model = Portfolio(CMSPlugin) module = _("Portfolio") name = _("Portfolio Plugin") # name of the plugin in the interface render_template = "portfolio_cms_integration/portfolio_plugin.html" cache = False def render(self, context, instance, placeholder): context.update({'instance': instance}) return context portfolio_plugin.html <div class="filters-content"> <div class="row grid"> {% for p in instance.portfolio.all %} <div class="single-portfolio col-sm-4 all vector"> … -
Why do I get 'CSRF Token Missing or Incorrect' error for Javascript Request
I am trying to create request in Javascript when a button is clicked but instead receive the error Forbidden (CSRF token missing or incorrect.). I have included {% csrf_token %} in the HTML template: <form action="/cart" method="POST"> {% csrf_token %} <button type="button" id="ordered">Place Order</button> </form> But am unsure if I have to include it in my Javascript request: const request = new XMLHttpRequest(); request.open("POST", "/cart"); // send request let data = new FormData(); items = localStorage.getItem(user + "items") total = localStorage.getItem(user + "price") data.append("items", items) data.append("total", total) request.send(data); In my views.py: def cart(request): if request.method == "POST": data = request.get_json() print(f"{data}") return HttpResponseRedirect(reverse("index")) else: return render(request, "cart.html") -
Authentication with Vue JS and Django?
I'm working on a small university project with Vue JS, Django2, Django Rest Framework where I have 2 differents rol for the users so they can do differents action in the application. I'm confused on the login part. I don't know how work with both frameworks(Vue and django) for the authentication in my project. I've read about JWT, I understand how it works but I haven't used before. If there is not another way to work with the auth I'll user JWT. Is there another way to work with authentication with both frameworks? -
Django: Populating serialized field if model field's foreign key relationship exists
Let's say I have 3 models: class MeterialPricing(models.Model): list_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) book_pricing = models.ForeignKey('books.BookPricing', null=True, blank=True) inventory_pricing = models.ForeignKey('store.InventoryPricing', null=True, blank=True) class BookPricing(models.Model): list_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) class InventoryPricing(models.Model): list_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) And a serializer class: class MaterialPricingSerializer(ModelSerializer): class Meta: model = MaterialPricingShell fields = ('pk', 'list_price',) As you can see, right now, the serialized list_price is coming from the MaterialPricing model. If BookPricing or InventoryPricing list_price exists, I want to set the serialized list_price to be one of these. The list_price in BookPricing has the most priority, then the InventoryPricing, and if both of these are null, then we can just have the list_price be the list_price on the MeterialPricing model. I was looking into using SerializerMethodField(), but I'm not sure if there is a post hook of something kind to look if the list_price exists on the BookPricing or InventoryPricing models. -
urlconfig - It takes Default parameter, not the passing one
if I pass http://127.0.0.1:8000/call/?p=3 and i print num in view.page it prints 1 #urls.py urlpatterns = [ path('call/',views.call), path('call/page<int:num>/',views.call), ] if I pass 127.0.0.1:8000/call/?p=3 and it prints num 1 and not 3. # View (in blog/views.py) def page(request, num=1): print(num) // 1 -
CSRF Cookie not set error on React Native Front end with Django Back end
I have a react native application which has Django as it's back end. I am using django-allauth along with django-rest-auth to handle social login in the app. In the app, apart from Social Login/Signup, a user can also do the regular sign up using email and password. The API for Regular Sign Up works every time as many times it is being called,a new user is being created on the DB. When signing up via Facebook, the user is created on the DB. But after this first successful hit, all of the hits that follow are met with 403 Forbidden with a message CSRF (Cookie/Token[I don't remember the error]) not set. And even the regular sign up API also starts receiving this same error. Both the React Native Development Workstation and Django Backend workstation are on the same network. I have tried csrf_exempt but it does not have any effect.Is it due to improper logout ? What other things am I missing with respect to django-allauth/django-rest-auth library ? Any help would be appreciated. -
can I serve a python 2.7 and a 3.6 django website at the same time with the same User database?
I have an old python 2.7 with Django 1.8 website running for years, it would be a lot of works to do if I upgrade it to python 3 and a new version Django, since there are a lot of apps on it not compatible with python 3. And I need to use channels. It looks like I'd better use python 3.6+ and the new version of Django. So I could only create a new site rather than create an app for the old website. Can I serve a new website, and share the old database to it so that the users can use the new one directly? -
Django: Why is my ModelForm not displaying any value to my instance?
I have created a modelform with a single text field. I instantiate this with my model object. When I render my form, there is no field with my object PK. Therefore how does the form know which model object it refers to? forms: class InterForm(forms.ModelForm): inter = forms.CharField( widget=forms.Textarea(attrs={'rows': 6, 'cols': 160}), label='', required=True) class Meta: model = Sample fields = ('id', 'interpretation',) def __init__(self, *args, **kwargs): super(InterForm, self).__init__(*args, **kwargs) views: interpretation_form = self.interpretation_form(instance=self.crs_obj) display: <tr><th></th><td> <textarea name="interpretation" cols="160" rows="6" required id="id_interpretation"> </textarea></td></tr> why doesnt this have my id as the PK displayed by the form? So when I submit it the model object can be saved with the interpretation field? -
Simple Django Join
I'm quite frustrated by now. I'm trying to do a really simple query to two models. My goal is simply to join A and B, in SQL I would do it like: SELECT * FROM A JOIN B ON A.x = B.z My models look roughly like class A(models.Model): x = id class B(models.Model): z = ForeignKey(A) I want a cross product from A and B and not just a filter. Can please somebody help me out? I'm sure the solution is more than obvious but I can't find it. -
How can I get a form field attribute from within the form element and use it's value to set a nested div's id?
I am new to Django and am struggling with the modelformset. I have read the documentation and looked through StackOverflow, etc. and cannot seem to find a solution to the following problem. I have a Django modelformset in my template, the forms of which I display with a for loop. I would like to display each form in its own div and I would like each div to have a unique id which relates it to the form it contains -- to do this I have a "form_id" field in the model the modelformset uses (the field is hidden to the user) that I want to access and use to dynamically assign a value to the div's id (see template code below). However, I cannot seem to access the form's "form_id" field for use in the div id. {% for form in incident_formset %} <div id=""> <fieldset> <legend>Report</legend> {% crispy form %} <input type="button" id="" value="Delete Report"> </fieldset> </div> {% endear %} In the above code, I would like to have the id of the divs to be "form_form_field_value" and "delete_form_form_field_value" respectively. I have tried getting the value with form.form_id.value among other combinations and concatenating that value with the id … -
How to force two buttons into one line
Below you see the cell where the buttons (bootstrap 4) are. The other cells were not printed. The EDIT and DELETE button are one over the other (2 lines). How to force them to the same line? <div class="container"> <table class="table table-striped"> ..deleted... <tbody> ..deleted... <tr> <div> <form method="GET"> {% csrf_token %} <button class="btn btn-outline-secondary btn-sm" type="submit" name="edit" value={{objekt.id}}>Edit</button> </form> <div id="colwrap"> <form method="POST"> {% csrf_token %} <button class="btn btn-outline-secondary btn-sm" type="submit" name="delete" value={{objekt.id}}>Delete</button> </form> </div> </div> </tr> </tbody> </table> </div class="container"> -
How to create a table with two fields as User model type
I'm trying to make a messaging app in my django project, I want the table to have three fields, "sender" "title" "message" "reciever". Title and Message can be declared as char-field. But I cannot make sender and receiver as two ForeignKey Field. I don't know what to use here. Can anyone help me figure this out? I tried to declare both field as ForeignKey with user model. But it didn't worked. from django.db import models from django.contrib.auth.models import User # Create your models here. class msgs(models.Model): to = models.OneToOneField(User, on_delete=models.CASCADE) frm = models.OneToOneField(User, on_delete=models.CASCADE) title = models.CharField(max_length = 255) body = models.CharField(max_length=2000) ERRORS: msgs.msgs.frm: (fields.E304) Reverse accessor for 'msgs.frm' clashes with reverse accessor for 'msgs.to'. HINT: Add or change a related_name argument to the definition for 'msgs.frm' or 'msgs.to'. msgs.msgs.frm: (fields.E305) Reverse query name for 'msgs.frm' clashes with reverse query name for 'msgs.to'. HINT: Add or change a related_name argument to the definition for 'msgs.frm' or 'msgs.to'. msgs.msgs.to: (fields.E304) Reverse accessor for 'msgs.to' clashes with reverse accessor for 'msgs.frm'. HINT: Add or change a related_name argument to the definition for 'msgs.to' or 'msgs.frm'. msgs.msgs.to: (fields.E305) Reverse query name for 'msgs.to' clashes with reverse query name for 'msgs.frm'. HINT: Add or … -
Gel all the values of Many2Many intermediate table with their respective name
I have the following database structure: Products -------- id name 1 prodA 2 prodB Products_Invoices ----------------- product_id Invoice_id 1 1 2 1 Invoices -------- id name 1 InvA 2 InvB Which is most correct way to retrieve all the values of the Products_Invoices table but bring the names of their respective row in parent tables. -
How to fix 'Not found The requested resource was not found on this server.', faced when serving django website using nginx?
I have hosted my website www.gojainyatra.com made with django, served using nginx. While some of the pages are opening correctly, there are some pages which give error, e.g. https://www.gojainyatra.com/dharamshala/firstshala/vlogs/2019/6/20/5/9/46/test/ Not found The requested resource was not found on this server My nginx configuration: upstream app_server { server unix:/home/gojainyatra/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name gojainyatra.com www.gojainyatra.com; keepalive_timeout 5; client_max_body_size 4G; access_log /home/gojainyatra/logs/nginx-access.log; error_log /home/gojainyatra/logs/nginx-error.log; location /static/ { alias /home/gojainyatra/staticfiles/; } # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } I don't know why this is happening, please help.