Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to keep DRY while creating common models in Django?
For example I have 2 main models in my django app: class Employee(Model): name = CharField(max_length=50) class Client(Model): title = CharField(max_length=50) Abstract base class for phones: class Phone(Model): number = CharField(max_length=10) class Meta: abstract = True Inherited separate classes for Employee and for Client: class EmployeePhone(Phone): employee = ForeignKey(Employee, on_delete=CASCADE, related_name='employee_phones') class ClientPhone(Phone): client = ForeignKey(Client, on_delete=CASCADE, related_name='client_phones') It works but I don't like it, I would prefer to keep just one Phone model instead of 3. I know I could use Generic-Models but unfortunately that's not longer an option, because my app is actually REST-API and it seems to be impossible to create Generic-Object while creating Parent-Object. So is there any solution to keep things clean and DRY ? -
django heroku amazon s3 bad request (400)
I have recently published a website in heroku using django and amazon s3 for static files. The website loads ok but when I visit some pages of my website I get a bad request (400) error message. Here is the heroku error log: 2018-03-15T11:40:23.414590+00:00 app[web.1]: 10.225.52.12 - - [15/Mar/2018:11:40:23 +0000] "GET /%CE%B5%CF%80%CE%B9%CE%BA%CE%BF%CE%B9%CE%BD%CF%89%CE%BD%CE%AF%CE%B1/ HTTP/1.1" 400 26 "https://matakiaslifts.herokuapp.com/%CE%B5%CE%B3%CE%BA%CE%B1%CF%84%CE%AC%CF%83%CF%84%CE%B1%CF%83%CE%B7/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36" Any help will be appreciated! -
Django all lauth multiple user type
Im trying to implement two user types while using all-auth out of the box with django 1.11 cookiecutter. Ive tried the solution here Multiple user type sign up with django-allauth But the seeker type one to one relationship is never created only the user. Anyone implement this before? TIA Models from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ import config.settings.base as settings @python_2_unicode_compatible class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_('Name of User'), blank=True, max_length=255) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username}) class Seeker(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_location = models.ForeignKey('location.Location', null=True, blank=True) class Meta: verbose_name = "Seeker" verbose_name_plural = "Seekers" def __str__(self): return self.user.username Form from allauth.account.forms import SignupForm from .models import Seeker, Employer class SeekerSignUpForm(SignupForm): def save(self, request): # Save the User instance and get a reference to it user_seeker = super(SeekerSignUpForm, self).save(request) # Create an instance of your model with the extra fields # then save it. # (N.B: the are already cleaned, but if you want to do some # extra cleaning just override the clean method … -
SchemaGenerator get_description(...) where is it now?
Updated to Django Resto Framework 3.7.7 and got to updating the legacy code when I came about this pearl: def get_description(self, path, method, view) In the SchemaGenerator class. This method was called from another class in the legacy code that inherits from SchemaGenerator. I have spent hours looking to see where it was moved to or if there's an alternative for that, but I can't seem to find anything on the documentation. Places I've looked: http://www.django-rest-framework.org/topics/release-notes/#37x-series https://github.com/encode/django-rest-framework/search?q=SchemaGenerator&type=Commits&utf8=%E2%9C%93 I see that a new class has been added called AutoSchema with the function get_description() problem is I don't know why it was created or if it's meant to substitute SchemaGenerator (until it goes deprecate). I am having a hard time finding information on this. I'd appreciate if anyone pointed me in the right direction. -
Django prefetch_related multiple queries
I'm using prefetch_related to join three tables. Products, ProductPrices and ProductMeta. But besides I'm following the documentation, the debugger says that I'm using three queries instead of one (with joins) Also this creates a second problem. Some products doesn't have prices in some countries because they are not avaliable there. But using this code, the product appears but with an empty price. So, I'd like to do all in one query with joins, and also I'd like to exclude the products that doesn't have prices or meta. I'm doing something wrong? This is my code: prefetch_prices = Prefetch( 'product_prices', queryset=ProductPrices.objects.filter(country=country_obj), to_attr='price_info' ) prefetch = Prefetch( 'product_meta', queryset=ProductMeta.objects.filter(language=lang), to_attr='meta_info' ) products = Product.objects.prefetch_related(prefetch, prefetch_prices).all() That produces these SQL Queries: { 'sql': 'SELECT DISTINCT `products`.`id`, `products`.`image`, ' '`products`.`wholesale_price`, `products`.`reference`, ' '`products`.`ean13`, `products`.`rating`, `products`.`sales`, ' '`products`.`active`, `products`.`active_in`, ' '`products`.`encilleria`, `products`.`delivery`, ' '`products`.`stock`, `products`.`ingredients`, ' 'FROM `products` WHERE `products`.`active` = 1 ', 'time': '0.098'}, { 'sql': 'SELECT `products_meta`.`id`, `products_meta`.`product_id`, ' '`products_meta`.`name`, `products_meta`.`slug`, ' '`products_meta`.`tagline`, `products_meta`.`key_ingredients`, ' '`products_meta`.`ideal_for`, `products_meta`.`description`, ' '`products_meta`.`advice`, `products_meta`.`summary`, ' '`products_meta`.`language` FROM `products_meta` WHERE ' "(`products_meta`.`language` = 'en' AND " '`products_meta`.`product_id` IN (52001, 51972, 52038, 52039, ' '52040, 52041, 51947, 51948, 51949, 51950, 51951, 51953, 51954, ' '51832))', 'time': '0.096'}, { 'sql': … -
Where the `csrftoken` store in Django database?
Where the csrftoken store? when I access a API endpoint (logout API, it do not need the params): POST /rest-auth/logout/ HTTP/1.1 Host: 10.10.10.105:8001 Connection: keep-alive Content-Length: 0 Accept: application/json, text/plain, */* Origin: http://localhost:8080 Authorization: Token 0fe2977498e51ed12ddc93026b08ab0b1a06a434 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36 Referer: http://localhost:8080/register Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9,en;q=0.8 Cookie: sessionid=b95zopro0qvkrexj8kq6mzo1d3z2hvbl; csrftoken=z53lKL0f7VHkilYS5Ax8FMaQCU2ceouje9OeTJOgTy4gH0UgHVltAlOe2KFNNNB6 the header is upper. In the Response I will a error: {"detail":"CSRF Failed: CSRF token missing or incorrect."} So, the backend must verified the csrftoken. in the backend database, I can not find the csrftoken field: whether it is saved in the encrypted session_data? -
Internet shop in django. How to filter orders by user?
For my project i wrote account, cart, orders and shop apps. order/models: from django.db import models from shop.models import Product class Order(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) postal_code = models.CharField(max_length=20) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created',) def __str__(self): return 'Order {}'.format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price * self.quantity account/models is empty account/views: from django.contrib.auth import login as auth_login from django.shortcuts import render, redirect from .forms import SignUpForm from orders.models import OrderItem, Order from django.contrib.auth.decorators import login_required def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() auth_login(request, user) return redirect('/') else: form = SignUpForm() return render(request, 'accounts/signup.html', {'form': form}) @login_required def account(request): my_orders = Order.objects.all() order_items = OrderItem.objects.all() return render(request, "accounts/my_acc.html", {"my_orders": my_orders, "order_items": order_items}) As you can see in account function i get all orders , but i don't know how to filter orders for user. What do i want is - when user enter in his … -
How do I hide or show content for each iteration?
I have a Lecture model which contains lectures. For each lecture I have a title and a content and eventually some files. I was trying to make that when somebody presses on a title, the title and the content will display under, but only for that lecture. Problem is that if I use a class, all lectures will be shown and if I use and id only the first one will be shown. How should I do this ? $('#title').click(function () { $('#lecture-hide').toggle(); }); {% for c in category.list %} <div id="title"> <p>Lecture {{ forloop.counter }}: <span>{{ c.lecture_title }}</span> </p> <br> </div> <div id="lecture-hide" style="display: none;"> <br> <li><h5>{{ c.lecture_title }}</h5></li> <li><p>{{ c.content }}</p></li> {% for file in c.files.all %} {% if file.files %} {% if forloop.first %} <p id="files">Lecture files:</p> {% endif %} <li><a class="media" href='{{ MEDIA_URL }}{{ file.files.url }}'><i class="fas fa-download"></i>{{ file.files.name }}</a></li> {% endif %} {% endfor %} <br> </div> {% endfor %} -
How to Save token in Shared Preferences received in Headers from DJango Rest Api
I am using volley in android.I am sending username and password to DJango rest Api and I get Token in Response.I need to get this Token from response Headers and save into sharedpreferences.How to get this Token from Headers and save it ? JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (error != null) { // Log.d(TAG, error.toString()) //Toast.makeText(getActivity(), "Enter Valid Username and Password", Toast.LENGTH_LONG).show(); coolToast.make("Invalid Details !",CoolToast.DANGER); coolToast.setRounded(true); coolToast.setDuration(CoolToast.SHORT); } } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<>(); String credentials = name+":"+pass; String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); headers.put("Content-type", "application/json"); headers.put("Authorization", auth); return headers; } } }; -
Implement django-filter MultipleModelChoiceField for reverse relationship lookup?
I have been using django-filters for one of my project. As per documentation I have implemented a Product filter(for colours and material) for my product models. But after much try still cannot implement reverse look for product sizes which is in another table ProductSize models.py class Product(models.Model): product_name = models.CharField(max_length=500) product_color = models.ForeignKey(Colour,related_name='productcolor') product_material=models.ForeignKey(Material) def __str__(self): return self.product_name class ProductSize(models.Model): product=models.ForeignKey('Product',related_name='details') value = models.CharField(max_length=50) stock= models.IntegerField(default=1) items_sold = models.IntegerField(default=0) description = models.TextField(blank=True) def __unicode__(self): return self.value class Colour(models.Model): colour=models.CharField(max_length=100) colour_code=models.CharField(max_length=100,null=True,blank=True) def __unicode__(self): return u'%s' %self.colour class Material(models.Model): material=models.CharField(max_length=100) def __unicode__(self): return u'%s' %self.material filters.py class ProductFilter(django_filters.FilterSet): product_material=django_filters.ModelMultipleChoiceFilter(queryset=Material.objects.all(), widget=forms.CheckboxSelectMultiple) product_color=django_filters.ModelMultipleChoiceFilter(queryset=Colour.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = Product fields=['product_color','product_material'] views.py def product_view(request): product=Product.objest.all() f = ProductMaterialFilter(request.GET, queryset=product) context={'filter':f,} return render(request,'product.html',context) django versions==1.10.8 django-filter==1.1.0 I need to know steps for size filtering by 'value' of ProductSize models for ProductFilter enter image description hereAny help would be much appreciated.. Thankyou -
How to get a nested data from different models in django.?
In my webpage, i need to click on a link that takes me to the list of college names....then by selecting the name it needs to take me to the list of departments available in the particular college..then by choosing a department it needs to take me to the list of available blood groups ...then by choosing a blood group it needs to take me to the list of students available for the particular blood group...!! these should be linked on a chained manner..!! how can i do this with the help of models...please give me some suggestions friends..!! iam a learner..!! -
Custom migrations in Django
Django provides a really nice feature called makemigrations where it will create migration files based on the changes in models. We are developing a module where we will want to generate custom migrations. I haven't found much info about creating custom migrations in the Django docs. There is documentation on the various Operation classes that can yield migrations but there's nothing about creating custom Operation classes that can yield custom migrations. The autodetector module for generating new migrations also doesn't seem to leave much room for adding custom Operation classes: https://github.com/django/django/blob/master/django/db/migrations/autodetector.py#L160 It seems this is completely static. Are there other ways to generate custom migrations, perhaps by using existing classes with a custom management command? -
Django join-like query with no where condition
Say I have 3 models in Django class Instrument(models.Model): ticker = models.CharField(max_length=30, unique=True, db_index=True) class Instrument_df(models.Model): instrument = models.OneToOneField( Instrument, on_delete=models.CASCADE, primary_key=True, ) class Quote(models.Model): instrument = models.ForeignKey(Instrument, on_delete=models.CASCADE) I just want to query all Quotes that correspond to an instrument of 'DF' type. in SQL I would perform the join of Quote and Instrument_df on field id. Using Django's ORM I came out with Quote.objects.filter(instrument__instrument_df__instrument_id__gte=-1) I think this does the job, but I see two drawbacks: 1) I am joining 3 tables, when in fact table Instrument would not need to be involved. 2) I had to insert the trivial id > -1 condition, that holds always. This looks awfully artificial. How should this query be written? Thanks! -
get data based on primary key and display in html
I am trying to get data based on primary key and display for EDIT in html page. but i am getting 'QuerySet' object has no attribute '_meta' error. I try to resolve it by looking at other posts but unable to do so.. hope somebody will help in problem. my forms: class StudentForm(forms.ModelForm): class Meta: model = Student fields = ('stuName','stuCity','stuPhone','stuNationality','stuCreatedt') class CourseForm(forms.ModelForm): class Meta: model = Course fields = ('courseId','courseName','enrolledStu','students','dept') class DeptForm(forms.ModelForm): class Meta: model = Dept fields = ('deptId','deptName') Models.py class Student(models.Model): stuName = models.CharField(max_length=100) stuCity = models.CharField(max_length=100) stuPhone = models.IntegerField(max_length=10) stuNationality = models.CharField(max_length=50) stuCreatedt = models.DateTimeField(default=timezone.now) def __str__(self): return '%s %s %s' % (self.stuName,self.stuCity,self.stuNationality) Class Dept : class Dept(models.Model): deptId = models.AutoField(primary_key=True) deptName = models.CharField(max_length=100) def __str__(self): return '%s %s' % (self.deptId, self.deptName) class Course class Course(models.Model): courseId = models.AutoField(primary_key=True) courseName = models.CharField(max_length=100) enrolledStu = models.IntegerField(max_length=3) students = models.ManyToManyField(Student) dept = models.ForeignKey(Dept, on_delete=models.CASCADE) def __str__(self): return '%s %s %s %s' % (self.courseName,self.enrolledStu,self.students,self.dept) urls.py for edit is url(r'^stuApp/(?P\d+)/$', views.edtStudent, name='edtStudent'), method for edit inside view.py is : def edtStudent(request,pk): course = Course.objects.filter(pk=1).prefetch_related('students').select_related('dept') if request.method =="POST": form = CourseForm(request.POST,instance=Course) if form.is_valid(): course = form.save(commit=False) course.courseName = request.POST['courseName'] course.enrolledStu = request.Post['enrolledStu'] course.save() course.save_m2m() return redirect('liststudent') else: #form = CourseForm() #return … -
can't install pandas using docker-compose
I don't know if this is docker-related or pandas or me. I have a docker container for Django that worked perfectly fine, up until the point I needed to add Pandas. I have tried to install via requirements.txt as follows: Django>=2.0 psycopg2 python-decouple>=3.1 selenium>=3.7.0 ipdb==0.10.3 argon2-cffi>=18.1.0 django-widget-tweaks>=1.4.1 pandas==0.22 with the RUN pip install -r requirements.txt command in the Dockerfile. This works for all other python packages I've tried but not for pandas. Then I tried to run the command from the Dockerfile with different variations of RUN apt-get update && apt-get install -y python3-pandas or RUN pip install pandas No matter the approach, I try to run docker-compose up on the Django container and I get ImportError: no module named pandas Would appreciate any insight. -
Openedx Native installation : theme change not working
I have installed openedx using Native installation method. Now I want to change the default logo. As a test, i removed the logo from the folder /edx/app/edxapp/edx-platform/lms/static/images. But when i open the localhost, its still there. (lms view). In inspect view, the logo name appears as /static/images/logo.b6c374d66d57.png. The same operation when I perform in devstack, The logo changes successfully. What am I missing? Since I am using the default theme, I think I don't need to configure anything regarding theme customization. -
Does "to_internal_value" work for generic fields in Django REST Framework?
to_internal_value usually get a dict with data and return class object, but in django's generic models, you must provide object_id, but how will you provide an object_id if it's not created yet ? -
Combine two distinct views into a single page in django
Old setup object_list.html and object_edit.html used their own views and functionality was split on two separate pages # views.py class ObjectList(ListView): def get_context_data(self, **kwargs): ... def get_queryset(self): ... class ObjectUpdate(UpdateView): def get_object(self, queryset=None): ... def get_form(self, form_class=None): ... def form_valid(self, form): ... def get_form_class(self): ... # urls.py url(r'^objects/$', ObjectList.as_view(), name='object-list'), url(r'^objects/(?P<pk>[^/]+)/edit/$', ObjectUpdate.as_view(), name='object-edit'), New We want to split list and edit into smaller components and include them in a single base html file. e.g. object_base.html and ObjectBase {% include "object_list.html" %} {% include "object_edit.html" %} class ScheduleBase(???): template_name = "object_base.html" What is the correct way to combine or import existing views into a single page? Should I just combine them into a single view while doing other refactoring? -
NOT NULL constraint failed: user_profile.user_id
I'm try to make Sign Up form With Profile Model and I will make some changes in the model. All tables are created when I run manage.py makemigrations but when I want to run manage.py migrate then is show this error: django.db.utils.IntegrityError: NOT NULL constraint failed: user_profile.user_id Model.py class Profile(models.Model): user = models.OneToOneField(User,default="", on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() Views.py: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user.refresh_from_db() user.profile.birth_date = form.cleaned_data.get('birth_date') raw_password = form.cleaned_data.get('password1') user.save() user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) form.py: class SignUpForm(UserCreationForm): birth_date = forms.DateField(help_text='Required. Format: YYYY-MM-DD') class Meta: model = User fields = ('username', 'birth_date', 'password1', 'password2', ) -
Django authenticate always return None
Found a lot of questions about it however couldn't find smth helps me. Settings.py contains Authentication Backend: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) And auth user model: AUTH_USER_MODEL = 'users.User' User model inherits from AbstractUser class: class User(AbstractUser): <some_fields> And then 3 type of users inherit from User. I registered Client: class Client(User, models.Model): status = models.CharField(max_length=1, default='C', editable=False) <some_fields> When I activate user by activation link everything is OK. Client is authenticated user. However when I just try to enter by login and password authenticate always return None: class LoginView(APIView): def post(self, request): qs = User.objects.filter(Q(email=request.data.get('user')) | Q(phone=request.data.get('user'))) if qs.exists(): username = qs.first().username password = request.data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) return Response(CMD(user.id), status=status.HTTP_200_OK) return Response({ 'error': 'Invalid login / password', }, status=status.HTTP_400_BAD_REQUEST) I've logged qs which returned desired Client, also username and password are ok, but authenticate returns None. I think maybe problem is that Client isn't registered properly. This is the SignUp form: class ClientSignupForm(forms.ModelForm): class Meta: model = Client exclude = [ 'username', 'date_joined', ] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(ClientSignupForm, self).__init__(*args, **kwargs) def clean(self): <actions to validate captcha> def save(self): username = 'user' + str(User.objects.all().aggregate(Max('id'))['id__max'] + 1) … -
Getting and saving value from POST with nested serializer
class InfoSerializer(serializers.ModelSerializer): class Meta: model = EventInfo fields = ('email', 'pin') class EventSerializer(DataSerializer, GeoModelAPIView): # other fields event_info = InfoSerializer(read_only=True) def create(self, validated_data): event_info = validated_data.pop('event_info', {}) event = super().create(validated_data) EventInfo.objects.create(event=event, **event_info) return event Model class EventInfo(models.Model): pin = models.CharField(max_length=60, null=False, blank=False) email = models.EmailField() event = models.ForeignKey(Event) POST { # other data "event_info": { "email": "example@example.com", "pin": "1234567890" } } So I have a model that is not visible on the browsable API, but I want to be able to save data from POST request to that model. Using this code I can create the objects and it correctly links the info to a correct Event model. However the email and pin fields won't get saved. What I have figured out is that the 'event_info' data from the POST is not visible on the validated_data. The validation goes to the DataSerializer's validation method but I guess that I should somehow bypass the validation for just the 'event_info' data? -
Changing user data in django python
guys! I'm new to django and I'm developing simple web site with user registration. I want to test some things, for example: on user profile page I added picture: and by pressing on it picture should change to: And by pressing on red one it should be changed to grey. Condotion of this picture should be saved. I have seven pictures for every day of the week and user should be able to change every picture. I've created a model like this (if you have any better ideas it would be great): class Week1(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) utr_ust0 = models.IntegerField(default=0, max_length=3) utr_ust1 = models.IntegerField(default=0, max_length=3) utr_ust2 = models.IntegerField(default=0, max_length=3) ... utr_ust0 = 0 (grey) utr_ust0 = 1 (red) But I cant't really understand how to work with this model in views. I think that during registration I should do something like this: auth.login(request, user) Week1.objects.create(utr_ust0=0, utr_ust1=0, utr_ust2=0, utr_ust3=0, utr_ust4=0, utr_ust5=0, utr_ust6=0, user_id=username) But I get this error: invalid literal for int() with base 10: 'test5' And in the function that loads page with the calendar I'm returning dict like this: if request.user.is_authenticated: content['smiles'] = [Week1.utr_ust0, Week1.utr_ust1, Week1.utr_ust2, Week1.utr_ust3, Week1.utr_ust4, Week1.utr_ust5, Week1.utr_ust6] And of course I should add some ajax … -
Responsive navbar using Django, HTML, CSS, Javascript
I am following this guideline to create a responsive navbar that, according to the dimension of the screen, will show its elements in a dropdown list (instead of an inline, used for bigger screens). Below the relevant part of the HTML (replaced some useless parts with "..." to improve and speed-up readability) <!DOCTYPE html> <html lang="en"> <head> ... <link rel="stylesheet" href="{% static 'css/styles.css' %}"> <link rel="javascript" href="{% static 'javascript/responsive.js' %}"> </head> <body> {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %} {% block content %}<!-- default content text (typically empty) --> <!-- Main Logo --> <div class="main-image" id="myMainImage"> <img src="{{STATIC_URL}}/static/images/logo.png"/> </div> <!-- Navigation Bar --> <div class="topnav" id="myTopnav"> <a href <a href="#home" class="active">Home</a> <a href="http://www...</a></li> <a href="http://www.../">Storia di Gabriella</a></li> <a href="http://www...">Video Gallery</a></li> <a href="http://www...">Photo Gallery</a></li> <a href="http://www.../">Dicono di Noi</a></li> <a href="http://www...">Come Contattarci</a></li> <input type="text" placeholder="Ricerca.."> <a href="javascript:void(0);" class="icon" onclick="respScreen()">&#9776;</a> </div> in the static folder (mysite/articles/static) I have created a javascript folder with a responsive.js file inside it /* Toggle between adding and removing the "responsive" class to topnav when the user clicks on the icon */ function respScreen() { var x = document.getElementById("myTopnav"); if (x.className === "topnav") { x.className += " responsive"; } else { … -
Is it bad to dynamically create Django views?
I wanted to add a generic create form for every model in my app. After repeating the same few lines over and over only changing the model name the DRY principle called out to me. I came up with the following method to dynamically add a form, view, and route for each model in my app. forms.py from django import forms from . import models import inspect from django.db.models.base import ModelBase # Add ModelForm for each model for name, obj in inspect.getmembers(models): if inspect.isclass(obj) and isinstance(obj, ModelBase): vars()[name + "ModelForm"] = forms.modelform_factory(obj, exclude=()) views.py from . import forms from . import models import inspect from django.db.models.base import ModelBase def form_factory(request, form_type, form_template, redirect_url='index', save=True): if request.method == "POST": form = form_type(request.POST) if form.is_valid(): if save: form.save() return HttpResponseRedirect(reverse(redirect_url)) else: form = form_type() return render(request, form_template, {'form': form}) # Add view for each model for name, obj in inspect.getmembers(models): if inspect.isclass(obj) and isinstance(obj, ModelBase): form = getattr(forms, name + "ModelForm") func = lambda request: form_factory(request, form, 'core/create.html') name = 'create_' + name.lower() vars()[name] = func urls.py from django.urls import path from . import views from . import models import inspect from django.db.models.base import ModelBase existing_urls = [] for urlpattern in urlpatterns: … -
unable to add a variable as parameter in url with django
I'm using django ver. 2.0.3, with python 3.6 and following models @python_2_unicode_compatible class ArticleDb(models.Model): slug = models.SlugField(primary_key=True, unique=True, blank=True) title = models.CharField(max_length=200, validators=[MinLengthValidator(5)]) content = models.TextField(max_length=5000) then I have following template {% for article in articles %} <tr> <td>{{ article.title }}</td> <td><a href="{% url 'view_article' slug_addr= article.slug %}">{{ article.slug }}</a></td> </tr> {% endfor %} the url.py is following ... path('code/<slug:slug_addr>/', views.ViewArticle.as_view(), name="view_article"), ... so the problem is slug_addr= if I assign a string value it works but if I put template variables like article.slug don't works, althought {{article.slug}} works, every time I get this error: Reverse for 'view_article' with keyword arguments '{'slug_addr': ''}' not found. 1 pattern(s) tried: ['code\\/(?P<slug_addr>[-a-zA-Z0-9_]+)\\/$']