Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
View and Template for m2m with Through
In my app i need to store invoices (Invoice) of known products (Product) to calculate points for each seller (User). I'm trying to create form to insert basic invoice data plus inline form with sold products info. To handle it i create model like this: class Product(models.Model): group = models.CharField(max_length = 200, blank = False) mark = models.CharField(max_length = 200, blank = True) points = models.IntegerField(blank = False) class Invoice(models.Model): price = models.FloatField(blank=False) file = models.FileField(blank=False) product = models.ManyToManyField(Product, through='Sold') user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField() date_created = models.DateField(auto_now_add=True) date_updated = models.DateField(auto_now=True) class Sold(models.Model): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) I tried to manage it via django-admin and it work fine with admin.py: class ProductTabular(admin.TabularInline): model = Invoice.product.through class InvoiceAdmin(admin.ModelAdmin): inlines = [ProductTabular] exclude = ('product', ) class Meta: model = Invoice admin.site.register(Invoice, InvoiceAdmin) but i'm unable to create such form in own templates. Please, can you help me with views.py and template to get same result as for the django-admin? I tried via invoce form with inlineformset_factory for the Sold model, but i can't figure out how to save it. Thanks for any help! -
Django exception on server start up - module not found
I have searched online for other solutions with little luck. Posting here is a last resort. Everything was working well with my Django project. Then suddenly it stopped running the server as it used to. I'm not sure at all what I have done wrong. The issue is persistent across all of the git branches (it wasn't like this before) - making it even more confusing as the problem is not isolated to my branch only. Here is the error traceback: WARNINGS: ?: (1_7.W001) MIDDLEWARE_CLASSES is not set. HINT: Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middleware.AuthenticationMiddleware, and django.contrib.messages.middleware.MessageMiddleware were removed from the defaults. If your project needs these middleware then you should configure this setting. System check identified 1 issue (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001A7227EB598> Traceback (most recent call last): File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\utils\autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\core\management\commands\runserver.py", line 116, in inner_run self.check_migrations() File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\core\management\commands\runserver.py", line 168, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\db\migrations\executor.py", line 19, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\db\migrations\loader.py", line 47, in __init__ self.build_graph() File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\db\migrations\loader.py", line 185, in build_graph self.load_disk() File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\db\migrations\loader.py", line 103, in load_disk migration_module = import_module("%s.%s" % (module_name, migration_name)) … -
Connecting Foreign Key to URL in Django
I'm creating an online courses website, in which you create a course object and add chapter objects to it. Each chapter has a foreign key to a course object: class Course(models.Model): title = models.CharField(max_length=140, null=False) description = models.TextField(null=False) cover = models.ImageField(null=False) slug = models.SlugField(max_length=100, blank=True) pack = models.ForeignKey(CoursePack, on_delete=models.SET_NULL, null=True, blank=True) tag = models.ForeignKey(CourseGroup, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.title) super(Course, self).save(*args, **kwargs) def get_absolute_url(self): return reverse("course_detail", kwargs={'pk':self.pk,'slug': self.slug}) signals.pre_save.connect(instance_pre_save, sender="course.Course") class Chapter(models.Model): title = models.CharField(max_length=140, null=False) text = RichTextUploadingField() slug = models.SlugField(max_length=100, blank=True) course = models.ForeignKey(Course, on_delete=models.CASCADE, null=False, blank=False) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.title) super(Chapter, self).save(*args, **kwargs) def get_absolute_url(self): return reverse("chapter_detail", kwargs={'pk':self.pk,'slug': self.slug, "cpk":self.course.pk, "cslug":self.course.slug}) my view is like this: def chapter_view(request, pk, slug, cpk, cslug): context = {} chapter = Chapter.objects.get(pk=pk, slug=slug, cpk=cpk, cslug=cslug) context["chapter"] = chapter return render(request, "courses/chapter_detail.html", context) And here is the url path: re_path(r'^(?P<cslug>[-\w]+),(?P<cpk>\d+)/(?P<slug>[-\w]+),(?P<pk>\d+)/$', chapter_view, name='chapter'), And here is the anchor tag: <a href="{% url 'chapter' slug=chapter.slug cslug=chapter.cslug pk=chapter.pk cpk=chapter.cpk %}" >{{ chapter }}</a> I'm getting the error: FieldError at /cursos/name-of-the-course,course-pk-integer/name-of-the-chapter,chapter-pk/ Cannot resolve keyword 'cpk' into field. Choices are: course, course_id, id, slug, text, … -
Django Rest framework: I want my GET response to be a JSON object of links to all files in my media directory on my local machine. How do i do this?
My Project structure: myproject --* --* --media --* --* I want to allow users to access to my media directory: I want them to be able to read and download all files in my media directory and I want them to be able to write files to my media directory. How can I accomplish this using Django rest framework? Assume that there are 2 files in my media directory: I want to return the following JSON object as a response to a GET request: { file1: link_to_example1.txt } { file2: link_to_example2.txt } How do I do this -- what should my app's model.py, views.py and maybe serializers.py look like? -
Django reverse() producing AttributeError: 'URLPattern' object has no attribute '_populate'
I'm attempting to resolve a url using Reverse() (https://docs.djangoproject.com/en/2.0/ref/urlresolvers/), as shown here: auth_app/views.py def recurring_application_charge(request, *args, **kwargs): relative_uri = reverse('auth_app:activate_recurring_charge') print(relative_uri) return HttpResponse('test') def activate_recurring_application_charge(request, *args, **kwargs): return HttpResponse('test') This works fine in another app within the same project, yet in this app (auth_app) the following error is produced: Traceback (most recent call last): File "/Users/hidden/app_development/feed_me/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/hidden/app_development/feed_me/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/hidden/app_development/feed_me/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/hidden/app_development/feed_me/feedme/auth_app/views.py", line 427, in recurring_application_charge relative_uri = reverse('auth_app:activate_recurring_charge') File "/Users/hidden/app_development/feed_me/env/lib/python3.6/site-packages/django/core/urlresolvers/base.py", line 88, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/Users/hidden/app_development/feed_me/env/lib/python3.6/site-packages/django/core/urlresolvers/resolvers.py", line 565, in _reverse_with_prefix self._populate() File "/Users/hidden/app_development/feed_me/env/lib/python3.6/site-packages/django/core/urlresolvers/resolvers.py", line 433, in _populate url_pattern._populate() File "/Users/hidden/app_development/feed_me/env/lib/python3.6/site-packages/django/core/urlresolvers/resolvers.py", line 433, in _populate url_pattern._populate() AttributeError: 'URLPattern' object has no attribute '_populate' reverse_lazy() produces the same error. Surprisingly, url template tag works as expected i.e. {% url 'auth_app:activate_recurring_charge' %} urls.py from django.urls import path, include urlpatterns = [ path('auth_app/', include('auth_app.urls')), ] auth_app/urls.py from django.urls import path from . import views app_name = 'auth_app' urlpatterns = [ path('billing/recurring-charge/', views.recurring_application_charge, name='recurring_charge'), path('billing/recurring-charge/activate/', views.activate_recurring_application_charge, name='activate_recurring_charge'), ] Project structure is: |-- feed_me |-- env |-- feedme |-- auth_app |-- migrations |-- static |-- __init__.py … -
Reverse for ' ' with keyword arguments '{'pk': ''}' not found
Can anyone see a problem with these urls? my template is giving me an error but I can't find any reasons as to why this won't work. I'm able to print out the pk just fine inside of my template so I know that it's probably not a matter of passing context into my template from the view. Reverse for 'customer_company_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['accounts/detail/customer_company/(?P<pk>[0-9]+)/$'] Inside of my template I am able to print out the pk but for some reason my URL isn't showing that I'm actually passing it in. I think this is all you would need to see, but let me know and I can post more. Thank you for the help. config/urls.py (ROOTURLCONF) urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', auth_views.LoginView.as_view(template_name="accounts/login.html"),name="home"), # url(r'^$', views.HomePage.as_view(), name='home'), url(r'accounts/', include('apps.accounts.urls', namespace='accounts')), url(r'accounts/', include('django.contrib.auth.urls')), url(r'accounts/signup/$', SignUpView.as_view(), name='signup'), url(r'accounts/signup/carrier/$', CarrierSignUp.as_view(), name='carrier_signup'), url(r'accounts/signup/customer/$', CustomerSignUp.as_view(), name='customer_signup'), url(r'accounts/signup/agent/$', AgentSignUp.as_view(), name='agent_signup'), url(r'user_dashboard/', include('apps.user_dashboard.urls', namespace='user_dashboard')), url(r'customer_dashboard/', include('apps.customer_dashboard.urls', namespace='customer_dashboard')), url(r'^thanks/$', views.ThanksPage.as_view(), name='logout_confirmation'), url(r'login_success/$', views.login_success, name='login_success'), url(r'freight_projects/', include('apps.freight_projects.urls', namespace='freight_projects')), url(r'todos/', include('apps.todos.urls', namespace='todos')), url(r'locations/', include('apps.locations.urls', namespace='locations')), url(r'loads/', include('apps.loads.urls', namespace='loads')), url(r'quotes/', include('apps.quotes.urls', namespace='quotes')), # Autocomplete URLS url(r'^agent_autocomplete/$', AgentAutoComplete.as_view(),name='agent_autocomplete'), url(r'^carrier_autocomplete/$', CarrierAutoComplete.as_view(),name='carrier_autocomplete'), url(r'^shipper_autocomplete/$', ShipperAutoComplete.as_view(),name='shipper_autocomplete'), url(r'^consignee_autocomplete/$', ConsigneeAutoComplete.as_view(),name='consignee_autocomplete'), url(r'^customer_autocomplete/$', CustomerAutoComplete.as_view(),name='customer_autocomplete'), ] accounts/urls.py urlpatterns = [ # signup urls … -
django-oscar payment page not changing
I have an ecommerce application, which uses django-oscar. I want to implement paypal as a payment method which I have done everything from the docs and the problem is that the payment page keeps bringing the default payment page which includes a link to all the github page for every payment methods. I dont know why it is not changing to use paypal templates. below is my template settings. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), os.path.join(OSCAR_MAIN_TEMPLATE_DIR, 'templates'), OSCAR_MAIN_TEMPLATE_DIR, ... my file arrangement is src/ templates/ static/ manage.py ...... futher codes would be provided on request. -
How to override ModelChoiceField / ModelMultipleChoiceField default widget with a template for each choice
Background I have two models, Runs and Orders. One run will complete many orders, so I have a Many-to-one relation between my orders and runs, represented as a foreignkey on my orders. I want to build a UI to create a run. It should be a form in which someone selects orders to run. I'd like to display a list of checkboxes alongside information about each order. I'm using django crispy forms right now. views.py class createRunView(LoginRequiredMixin, CreateView): model = Run form_class = CreateRunForm template_name = 'runs/create_run.html' forms.py class CreateRunForm(forms.ModelForm): class Meta: model = Run fields = ['orders',] orders = forms.ModelMultipleChoiceField(queryset=Order.objects.filter(is_active=True, is_loaded=False)) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.layout = Layout( Field('orders', template="runs/list_orders.html"), Submit('save', 'Create Run'), Button('cancel', 'Cancel'), ) Questions I'm not sure what locals are available to me in the list_orders.html template. It seems like there's {{ field }} and maybe form.visible_fields but if I dig to deeply into either I get a TypeError: 'SubWidget' object is not iterable, which is barely documented online. The above suggests I might still be getting a widget in the template, despite the fact that Field('orders', template="runs/list_orders.html"), should prevent that, per the crispy docs: Field: Extremely useful … -
Warning because of old migration - how should that be solved?
If I run python -Wall manage.py test this warning (and similar) occurs: /local/lib/python2.7/site-packages/django/db/models/fields/__init__.py:1453: RuntimeWarning: DateTimeField SignUpUser.signup_time received a naive datetime (2018-03-17 21:27:22.620074) while time zone support is active.RuntimeWarning) But there is no such field for the model SignUpUser anymore. It's called signup_timestamp. The same error occurs on other fields. To fix these I changed datetime.now to the django built-in timezone considering timezone.now. But the error messages also doesn't disappear. I think this occurs because of an old migration. The site is already in production, but only me is developing. How should I fix this? Resetting all migration files and redo the migration with --fake-initial? -
Django ORM annotate with subquery
I've got following models: class Store(models.Model): name = models.CharField() class Goods(models.Model): store = models.ForeigKey(Store, on_delete=models.CASCADE) total_cost = models.DecimalField() different values ... So, I filtered all the goods according to the parameters, and now my goal is to get one good from each store, which has the lowest price among other goods from this store stores = Store.objects.all() - all stores goods = Good.objects.filter(..) - filter goods goods.annotate(min_price=Subquery(Min(stores.values('goods__total_cost')))) I tried something like this, but I've got an error: AttributeError: 'Min' object has no attribute 'query' -
Serializer field breaking unittest on Django/Python
I took a task to implement a new lookup on a query on a code I didn't write. Usually, the query would expect and query_param named 'sku'. I've make a change so the view would look for a 'sku' or an 'upc' param. It worked fine on the browser. But when I tried to run the tests, I saw 1 test was not passing. I begin to look what was wrong. The response.data on the test is waaay different when I have the 'upc' field on my serializer, like 3 times more lines. response.data WITH 'upc'field serialized response.data WITHOUT 'upc' field serialized The test: @mock.patch('order.views.OMSAPIManager', mock_api_manager(copy(static_data.oms_order), 200)) @mock.patch('order.utils.CatalogProductsViewSet') def test_retrieve_order(self, mock_product_viewset): mock_view_instance = mock_product_viewset.return_value mock_view_instance.retrieve.return_value = mock.Mock(data=copy(static_data.product_details)) response = self.client.get(reverse('order-detail', args=[1])) self.assertEqual(response.status_code, 200) self.assertDictEqual(loads(dumps(response.data)), self.expected_order_detail) Any help please? T_T -
display and update DateField using a custom form in django
i'm trying to display and update a DateField using my custom form , i'm using DATE_INPUT_FORMATS like that settings.py DATE_INPUT_FORMATS = ['%d %m %Y'] forms.py class UserForm(forms.ModelForm): birth_day = forms.DateField(input_formats=settings.DATE_INPUT_FORMATS) class Meta: model = User fields = ('first_name', 'last_name','birth_day') my custom inpute : <input type="text" name="birth_day" value="{{ user.birth_day }}" size="10" class="form-control date-picker" id="id_birth_day" data-datepicker-color=""> default form inpute <input type="text" name="birth_day" value="" required="" id="id_birth_day" class="form-control"> my problem starts everytime i'm trying to update the i have to re-enter the DateField since my DATE_INPUT_FORMATS is like that 06 02 2017 but django display it like that Feb 6th, 2017 so h so every time i update my form i get Enter a valid date. error so what it the best way to fix this problem and without changing the display and inpute format if possible -
Django M2M relationships one intermediary table per entity or I should pack them?
When creating many to many relationships we use an intermediary table. Lets say I use the following entities video, category, tag, and VideoCategory, VideoTag to create the relations. I'm assuming that many tags/categories can have many videos and vice-versa. And I do it with through keyword 'cause I want to be able to use extra fields in the future if I want. class Category(models.Model): category = models.CharField(max_length=50) def __str__(self): return self.category class Tag(models.Model): tag = models.CharField(max_length=50) def __str__(self): return self.tag class Video(models.Model): title = models.CharField(max_length=255) categories = models.ManyToManyField(Category, through='VideoCategory') tags = models.ManyToManyField(Tag, through='VideoTag') def __str__(self): return self.title class VideoCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) video = models.ForeignKey(Video, on_delete=models.CASCADE) class VideoTag(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE) video = models.ForeignKey(Video, on_delete=models.CASCADE) But I was wondering if would be possible to create a taxonomy entity and handle the relationships with categories and tags from just one site. class Category(models.Model): category = models.CharField(max_length=50) def __str__(self): return self.category class Tag(models.Model): tag = models.CharField(max_length=50) def __str__(self): return self.tag class Video(models.Model): title = models.CharField(max_length=255) categories = models.ManyToManyField(Category, through='Taxonomy') tags = models.ManyToManyField(Tag, through='Taxonomy') def __str__(self): return self.title class Taxonomy(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) tag = models.ForeignKey(Tag, on_delete=models.CASCADE, null=True) video = models.ForeignKey(Video, on_delete=models.CASCADE) Now the taxonomy entity would hold the … -
Django form gives error 500
I'm working now at multiple file upload and i have made a form. But when i check that is that form valid it gives me error 500. Here is code: views.py: def post(self, request): form = PhotoForm(request.POST, request.FILES) return HttpResponse(form.is_valid()) forms.py: class PhotoForm(forms.ModelForm): image = MultiImageField( min_num=1, max_num=50, max_file_size=429916160, ) class Meta: model = Photo fields = ('gallery',) -
Models.form : How to handle the list _meta exception in django
def profile_edit(request,username): profile_edit = get_object_or_404(User,username=username) userprofile = get_object_or_404(UserProfile, user__username=username) degree = get_list_or_404(Degree,education__user__username=username) **# how to handle this code** if request.user == profile_edit and request.user.is_authenticated: if request.method == "POST": form = EditForm(request.POST,instance=profile_edit) form1 = EditForm1(request.POST,instance=userprofile) form2 = EditForm2(request.POST,instance=degree) if form.is_valid() and form1.is_valid() and form2.is_valid(): form.save() form1.save() form2.save() **# how to handle this code** return redirect('profile_edit',username=username) else: form = EditForm(instance=profile_edit) form1 = EditForm1(instance=userprofile) form2 = EditForm2(instance=degree) context = {'form':form,'form1':form1,'form2':form,} return render(request,'userprofile/profile_edit.html', context) else: raise PermissionDenied In above code each user has multiple degree, which I need to process as a form in template to edit it and save it in database. Exception Value: 'list' object has no attribute '_meta' How to handle above exception ? ps :- I want education details to be editable in template -
Using a Django url reference inside a plotly/Dash application
I'd like to embedd an dash application in a django website. On my application page I'm setting up a navigation bar in which I'd like to include links to other parts of my website. I've tried the following, but I don't know how to refer the urls from within the dash application html.Nav( html.Ul( [html.Li( html.A("The link to Home",href="{% url 'app_name:home'%}), ] ), ) A link is properly shown, but when I click it the page is only refreshed. In my appname.urls.py file I have the following : urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home'), ] and of course I have the appropriate home.html template -
Print list value in loop in Django template
I am passing a list SLIDER list object into Django template and want to generate output as give below but it's not giving the same output. So, please guide me, friends. Thanks SLIDER = ['img1.png', 'img2.png', 'img3.png'] {% for img in SLIDER %} <img src="{%static "images/{{img}}"%}"/> {% endfor %} Output should be like: <img src="{%static "images/img1.png"%}"/> <img src="{%static "images/img2.png"%}"/> <img src="{%static "images/img3.png"%}"/> -
Django updateView saving another instance instead of updating
im trying to update my model but it just creates another instance and i cant figure out why. i was under the impression that all i needed was: class QuestionUpdate(generic.UpdateView): model = models.Question form_class = QuestionForm and it would take care of it for me but that doesnt seem to be the case. im in django 1.11 and running python 3.6. Any and all help is appreciated. models.py class Question(models.Model): class Meta: ordering = ['-date_updated'] # user = models.ForeignKey(User, related_name="question", default='') question = models.TextField(unique=False, blank=False, null=False) question_html = models.TextField(blank=False, null=False) answer = models.TextField(blank=False, null=False) answer_html = models.TextField(blank=False,null=False) date_created = models.DateTimeField(auto_now=True, null=True) date_updated = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.question # ^ to display an object in the Django admin site and # as the value inserted into a template when it displays an object. def save(self, *args, **kwargs): self.question_html = misaka.html(self.question) self.answer_html = misaka.html(self.answer) super().save(*args, **kwargs) views.py class QuestionUpdate(generic.UpdateView): model = models.Question form_class = QuestionForm # fields = ('question', 'answer') def edit_question(self, request, id): question = get_object_or_404(Question, id=id) form = QuestionForm(request.POST, instance=question) if form.is_valid(): form.save() forms.py class QuestionForm(forms.ModelForm): # your_name = forms.CharField(label='Your name', max_length=100) class Meta: fields = ("question", 'answer') model = models.Question -
Django order_by not working properly
I'm trying to get all the conversations ordered by it last message, but when I use the order_by clausule, the conversations are repeated. Query without order_by: conversaciones = Conversacion.objects.filter(usuarios=request.user) Result (Grouped by Conversations but not ordered by the most recent last message first): Query with order_by: conversaciones = Conversacion.objects.filter(usuarios=request.user).order_by('-mensaje__fechaEnvio') Result: My models.py: class Mensaje(models.Model): remitente = models.ForeignKey('Usuario', on_delete=models.CASCADE, related_name='remitente') destinatario = models.ForeignKey('Usuario', on_delete=models.CASCADE, related_name='destinatario') cuerpo = models.TextField(validators=[MaxLengthValidator(750)]) leido = models.BooleanField(default=False) fechaEnvio = models.DateTimeField(auto_now_add=True) conversacion = models.ForeignKey('Conversacion', on_delete=models.CASCADE) class Meta: ordering = ['-fechaEnvio'] def __str__(self): return str(self.remitente) + ' -> ' + str(self.destinatario) class Conversacion(models.Model): usuarios = models.ManyToManyField('Usuario', related_name='usuarios') agresion = models.ForeignKey('Agresion', on_delete=models.CASCADE) @property def ultimoMensaje(self): return self.mensaje_set.latest('fechaEnvio') -
Models.form : How to handle the list _meta exception in django
def profile_edit(request,username): profile_edit = get_object_or_404(User,username=username) userprofile = get_object_or_404(UserProfile, user__username=username) degree = get_list_or_404(Degree,education__user__username=username) # how to handle this code if request.user == profile_edit and request.user.is_authenticated: if request.method == "POST": form = EditForm(request.POST,instance=profile_edit) form1 = EditForm1(request.POST,instance=userprofile) form2 = EditForm2(request.POST,instance=degree) if form.is_valid() and form1.is_valid() and form2.is_valid(): form.save() form1.save() form2.save() # how to handle this code return redirect('profile_edit',username=username) else: form = EditForm(instance=profile_edit) form1 = EditForm1(instance=userprofile) form2 = EditForm2(instance=degree) context = {'form':form,'form1':form1,'form2':form,} return render(request,'userprofile/profile_edit.html', context) else: raise PermissionDenied In above code each user has multiple degree, which I need to process as a form in template to edit it and save it in database. Exception Value: 'list' object has no attribute '_meta' How to handle above exception ? ps :- I'm using latest version of django -
deploy Django application to heroku by GitLab
I have a Django repository on Django and want to deploy the application on Heroku. I was going through the documentation of GitLab https://docs.gitlab.com/ce/ci/examples/test-and-deploy-python-application-to-heroku.html#configure-project Which is asking to create two variables HEROKU_STAGING_API_KEY HEROKU_PRODUCTION_API_KEY It also states You'll need to create two variables in Project > Variables: and Find your Heroku API key in Manage Account (https://dashboard.heroku.com/account) The link to heroku dashboard revels only API key which might be used but for which variable, I'm not getting it. Also from where to get another variable value? Also there is no option like Project > Variables in GitLab project, so where should I create the specified variables? -
Models.form : How to handle the list _meta exception in django
def profile_edit(request,username): profile_edit = get_object_or_404(User,username=username) userprofile = get_object_or_404(UserProfile, user__username=username) degree = get_list_or_404(Degree,education__user__username=username) **# how to handle this code** if request.user == profile_edit and request.user.is_authenticated: if request.method == "POST": form = EditForm(request.POST,instance=profile_edit) form1 = EditForm1(request.POST,instance=userprofile) form2 = EditForm2(request.POST,instance=degree) if form.is_valid() and form1.is_valid() and form2.is_valid(): form.save() form1.save() form2.save() **# how to handle this code** return redirect('profile_edit',username=username) else: form = EditForm(instance=profile_edit) form1 = EditForm1(instance=userprofile) form2 = EditForm2(instance=degree) context = {'form':form,'form1':form1,'form2':form,} return render(request,'userprofile/profile_edit.html', context) else: raise PermissionDenied In above code each user has multiple degree, which I need to process as a form in template to edit it and save it in database. Exception Value: 'list' object has no attribute '_meta' How to handle above exception ? -
Django Deployment Fails: Heroku + Github Subdirectory
I'm trying to deploy my Django App in GitHub (with default Heroku integration for Github) but I'm having some problems. My project directory is allocated in a subfolder of my repo, that is: - Folder 1 - Folder 2 - Folder 3 - Folder 3.1 - Project - ... - manage.py - procfile - ... - Folder 3.3 - Folder 4 So every deployment fails with that log: ! No default language could be detected for this app. HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. See https://devcenter.heroku.com/articles/buildpacks ! Push failed There is some way to tell Heroku where is my project root ? -
Creating a navigation bar splitted in two parts with elements styled differently
I am trying to create a search button in a responsive navigation bar. The navigation bar has a media query in the CSS file that reduces it to a dropdown list according to the dimension of the reader's screen. The html of the navigation bar is the following <nav class="navbarSection"> <div class="topnav" id="myTopnav"> <a href="#home" class="active">Home</a> <a href="http://www.gabriellacipriani.it/chi-siamo-e-cosa-facciamo/">Chi Siamo e Cosa Facciamo</a> <a href="http://www.gabriellacipriani.it/storia-di-gabriella/">Storia di Gabriella</a> <a href="#articles">Tutti gli Articoli</a> <a href="http://www.gabriellacipriani.it/video-gallery/">Video Gallery</a> <a href="http://www.gabriellacipriani.it/photo-gallery/">Photo Gallery</a> <a href="http://www.gabriellacipriani.it/dicono-di-noi/">Dicono di Noi</a> <a href="http://www.gabriellacipriani.it/contatti/">Come Contattarci</a> <a href="javascript:void(0);" class="icon" onclick="respScreen()">&#9776;</a> <a class="material-icons" style="font-size:32px;color:white;">search</a> </div> </nav> And this is the CSS related /* Add a red background color to the top navigation */ .topnav { background-color: #aa2222; overflow: hidden; } /* Style the links inside the navigation bar */ .topnav a { float: left; display: block; color: #fff; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 15px; } /* Change the color of links on hover */ .topnav a:hover { background-color: #d9bb56; color: black; } /* Add an active class to highlight the current page */ .active { background-color: #d9bb56; color: white; } /* Hide the link that should open and close the topnav on small screens */ .topnav .icon { display: none; } … -
Create picture from other elements in table
I'm trying to create app where user can create picture from elements already existing in database, so there's no need to upload. User has a choice which elements he wants to be on the picture. So pic is an image created from Elements. So my question is, is it possible to do this like this? models.py class Picture(models.Model): owner = models.ForeignKey(User, on_delete= models.CASCADE) pic = models.ImageField(Elements, upload_to='media') title = models.CharField('title of your picture', max_length=50) created = models.DateTimeField('Date', auto_now_add= True) class Elements(models.Model): element1 = models.ImageField(upload_to=None) element2 = models.ImageField(upload_to=None) element3 = models.ImageField(upload_to=None) element4 = models.ImageField(upload_to=None) text = models.CharField('Text on the picture', max_length = 50) I'm a begginer in Python and django, and I'm trying to understand basics. Or do you have any advice or good sources about images and manipulating them in Django? In documentation I didn't find much. After go trough models, I'm planning to use Pillow.