Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
reverse for app_list error while customizing my admin
while customizing admin page in django facing this error " Reverse for 'app_list' not found. 'app_list' is not a valid view function or pattern name. " but i dont created a view named app_list i have created a directory named admin and created base_site.html file in it admin/urls.py from django.urls import path from .views import InvoiceList, MerchantUserList, SupportStatusUpdate from django.contrib import admin admin.autodiscover() urlpatterns=[ path( 'home/', admin.site.admin_view(InvoiceList.as_view()), name='home' ), path( 'user/list/', admin.site.admin_view(MerchantUserList.as_view()), name='user_list' ), path( 'support/update/<int:pk>/', admin.site.admin_view(SupportStatusUpdate.as_view()), name='support_update' ) ] -
How can I display category in http bar?
Working on eccomerce shop. I have created catogories fucntion which displays the items with particular category. All works fine, but I would like also to display the category name after /category/. I tried GET method but I get error. Any adivse? Value in the button is the Category. form in templates: <form method='post' action='/category/' class="form-inline"> {% csrf_token %} </li> <li class="nav-item"> <button class="nav-link purple darken-4" type="submit" name="S" value="S" style="background-color: grey;">Shirts</button> </li> <li class="nav-item"> <button class="nav-link purple darken-4" type="submit" name="S" value="O" style="background-color: grey;">Outwear</button> </li> <li class="nav-item"> <button class="nav-link purple darken-4" type="submit" name="S" value="SW" style="background-color: grey;">Sportwear</button> </li> </form> views: def category(request): if request.method=="POST": if request.POST.get('S', False): s = request.POST['S'] objects_display = Item.objects.filter(category=s) if objects_display.exists(): context ={ "objects": objects_display } return render(request, "shop/categories.html", context) else: messages.warning(request, 'no items found') return redirect('item-list') urls: path('category/', category, name='category'), -
I need help to make application with API server(Ubuntu)
I want to make application that have information from Ubuntu server. I don't know what to do in android studio. Do you have example or project for starter? I want to show data from Ubuntu server(Django) and make application. Please, help me.... -
Am I in the right track to become a web developer? [on hold]
long time ago I started learning web development by myself. First in HTML, CSS, JavaScript/JQuery and then Django I am also doing some Android. However, I am a computer science major so I do have a background on coding which made learning much easier. Still, I wonder if I am doing things the right way and where do I place myself in such a competitive field. I have no confidence in what I am doing and I think I might be wasting time because when looking at the jobs description in Glassdoor, all I see is companies looking for people who have minimum two to three years of experience. I have to to say that I do not have professional experience but only side projects that I do in my spare time. Now, my online resume is going to be the first serious project that "push" so I would like you to tell me what do you think about it. Of course, it looks ugly but it is uncompleted and is something that I am working on the side and it is just the beginning so give it a year and it will be completed. Please tell, am I in … -
Create models from database run time
In my Project we create new Databases dynamically. After the creat (which works fine) we need to create our models schema with inspectdb. I call de following python code. def trigger_after_extract(request): # inspectdb name = request.GET.get('project') command = 'python manage.py inspectdb --database ' + name + ' > api_manager/schemas/' + name + '.py' os.system(command) Now this code doesnt work. I already searched the Internet for some solution but couldnt find one. All I need to do is following: Durring run-time I need to create a model for a new Database with tables which are already created. I know that Inspectdb does exactly what I need but not durring run time is there a solution for the it? -
Model instances without primary key value are unhashable
I need to instantiate several model objects without actually creating them. They need to be added to a set but apparently: TypeError: Model instances without primary key value are unhashable What are my options here? -
How to route subdirectory based on country using Django
I want my Django application to work as a Subdirectory structure for my Subdomains. For example www.example.com/in www.example.com/ae Based on the country code we get, we will change currency & lang. -
How to display the contents of a table as a table in django?
I have made a simple django app. In my models.py I have defined a table- class events(models.Model): id_campaign = models.CharField(default='newevent',max_length=100) status = models.CharField(default='100',max_length=100) name = models.CharField(default='100',max_length=100) This is my views.py - from django.shortcuts import render # Create your views here. from django.views.generic import TemplateView from django.shortcuts import render from website.models import * from website.models import events from django.views.generic import ListView class HomePageView(TemplateView): template_name = 'base.html' class AboutPageView(TemplateView): template_name = 'about.html' class ContactPageView(TemplateView): template_name = 'contact.html' class Success(TemplateView): template_name = 'success.html' def MyView(self, request): query_results = events.objects.all() return render(request, self.template_name) And this is the success.html - {% if user.is_authenticated %} <header> <a href=" {% url 'logout'%}">Logout</a> </header> {% block content %} <h2>you are logged in successfully. this is your personal space.</h2> <table> <tr> <th>id_campaign</th> <th>status</th> <th>name</th> </tr> {% for item in query_results %} <tr> <td>{{ item.id_campaign }}</td> <td>{{ item.status }}</td> <td>{{ item.name }}</td> </tr> {% endfor %} </table> {% endblock %} {% else %} <h2>you are not logged in.</h2> {%endif %} My issue is that once the user logs in he is only able to see the hardcoded column names but the column values are not visible. It is as if the {% for item in query_results %}. part is not … -
How it is possible to create a billing record for a customer with woocommerce api
I can not post my information concerning a particular customer from my django app to my woocommerce site. The procedure that i am following is taking the information about billing from a form and then calling a function doing the post through the api to my site. I noticed that the billing information did not stored at all. Do you know if this behavior has to do with the syntax of the api? Do you know if I have to define the id of the customer in the posting command? my code: def create_woocommerce_client_billing_individually(wcapi,wholesale_client_id,first_name,last_name,company,address_1,address_2,city,state,postcode,country,email,phone): print(wholesale_client_id) fetched_billing=Woo_Customer_Billing.objects.get(client_id=wholesale_client_id,email=email) data = { "first_name": fetched_billing.first_name, "last_name": fetched_billing.last_name, "company": fetched_billing.company, "address_1": fetched_billing.address_1, "address_2": fetched_billing.address_2, "city": fetched_billing.city, "state": fetched_billing.state, "postcode": fetched_billing.postcode, "country": fetched_billing.country, "email": fetched_billing.email, "phone": fetched_billing.phone, } wcapi.post("customers", data).json() -
Best Way to Perform Addition and Multiplication on Django Fields
I have a model 'Manifests' and a form 'CreateManifestForm'. The user enters multiple lines of data in the CreateManifestForm and these are saved to the Manifest model (on a line by line basis, not using ajax or anything). There are 3 fields of concern in the model and form - 'Cases', 'FOB', 'CNF'. Both FOB and CNF are dollar amounts, so I'll use one as an example. How could I take the user entered FOB price, multiply it by cases and then store that number? Additionally, when the user enters another line, how could I do the same and then add that to the original number so I can get a total value. MODELS.PY class Manifests(models.Model): reference = models.ForeignKey(Orders) cases = models.IntegerField() product_name = models.ForeignKey(Products, default=None, blank=True, null=True) count = models.IntegerField() CNF = models.DecimalField(max_digits=11, decimal_places=2, default=None, blank=True, null=True) FOB = models.DecimalField(max_digits=11, decimal_places=2, default=None, blank=True, null=True) def __str__(self): return self.description VIEWS.PY def add_manifest(request, reference_id): form = CreateManifestForm(request.POST or None) if request.method == "POST": if form.is_valid(): instance = form.save(commit=False) try: order = Orders.objects.get(id=reference_id) instance.reference = order except Orders.DoesNotExist: pass instance.save() form = CreateManifestForm(initial={'reference': Orders.objects.get(reference=reference_id)}) reference = request.POST.get('reference') manifests = Manifests.objects.all().filter(reference=reference) context = { 'form': form, 'reference_id': reference_id, 'manifests' : manifests, } return … -
working with {% if %} {% else %} in Django
how can I hide user name from login page with If-Statement. Im using this code to show the user name in the main page after login in, and it's working {%if request.user.first_name%}{{request.user.first_name}}{%else%}{{user}}{%endif%} but the problem is that it's shown in the login page too as "AnonymousUser". how can I hide this Any Idea? -
The joined path is located outside of the base path component
There was a project on Django 1.9. I rewrote it on 1.11. But when I deploy to the server and collectstatic, I get an error django.core.exceptions.SuspiciousFileOperation: The joined path (/var/www/vhosts/finbee.freshlimestudio.com/assets/fonts/finbeeFont/fonts/finbeeFont.eot) is located outside of the base path component (/var/www/vhosts/finbee.freshlimestudio.com/static) All traceback here: PROJ_MODULE_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) ROOT = os.path.normpath(os.path.join(PROJ_MODULE_ROOT, "..")) root_path = lambda *args: os.path.join(ROOT, *args) path = lambda *args: os.path.join(PROJ_MODULE_ROOT, *args) STATIC_URL = '/static/' STATIC_ROOT = '' STATICFILES_DIRS = ( path('static'), ) STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) -
django updating user profile with custom form + display group name
I've got 2 questions: 1) I'm displaying a list of users w/ their group,and for the group name I got: ]> using {{instance.groups.all}} in my template. Any ideas to have only mygroup displayed? 2) For my update user form, I got an error and I don't know how and where to resolve it. error: updateUserView() got an unexpected keyword argument 'id' forms.py class UpdateForm(UserChangeForm): is_active = forms.BooleanField() Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ] group_name = forms.ChoiceField(choices=Group) class Meta: model = User fields = ('email', 'is_active', 'group_name', ) views.py def updateUserView(request): if request.method == 'POST': form = UpdateForm(request.POST, instance=request.user) if form.is_valid(): user = form.save() group = Group.objects.get(name=request.POST.get('group_name')) user.groups.add(group) return redirect('accounts:users') else: form = UpdateForm(instance=request.user) return render(request, 'accounts/update_user.html', {'form': form}) class UserView(LoginRequiredMixin, GroupRequiredMixin, ListView): template_name = 'accounts/display_users.html' group_required = ['Creators'] queryset = User.objects.filter(is_active=True) -
Django Channels dont sent message to Android App
I wanted to apply the official django channels tutorial from https://channels.readthedocs.io/en/latest/tutorial/part_2.html to a simple android app. At https://medium.com/@ssaurel/learn-to-use-websockets-on-android-with-okhttp-ba5f00aea988 I found a simple project but that uses the Echo WebSocket Server available at http://www.websocket.org/echo.html. I copy-pasted the same project but replaced the Echo WebSocket Server with my own websocket server using django channels. Here is the code: public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private Button start; private TextView output; private OkHttpClient client; private final class EchoWebSocketListener extends WebSocketListener { private static final int NORMAL_CLOSURE_STATUS = 1000; @Override public void onOpen(WebSocket webSocket, Response response) { Log.d(TAG, "onOpen() is called."); JSONObject obj = new JSONObject(); JSONObject obj2 = new JSONObject(); try { obj.put("message" , "Hello"); obj2.put("message", "Goodbye!"); } catch (JSONException e) { e.printStackTrace(); } webSocket.send(obj.toString()); //webSocket.send("What's up ?"); //webSocket.send(ByteString.decodeHex("deadbeef")); webSocket.close(NORMAL_CLOSURE_STATUS, obj2.toString()); } @Override public void onMessage(WebSocket webSocket, String text) { Log.d(TAG, "onMessage() for String is called."); output("Receiving : " + text); } @Override public void onMessage(WebSocket webSocket, ByteString bytes) { Log.d(TAG, "onMessage() for ByteString is called."); output("Receiving bytes : " + bytes.hex()); } @Override public void onClosing(WebSocket webSocket, int code, String reason) { Log.d(TAG, "onClosing() is called."); webSocket.close(NORMAL_CLOSURE_STATUS, null); output("Closing : " + code + " … -
Is it possible to combine the delete view with view which show posts in django?
I am in the process of creating an application in django and so far I have followed the "basic" paths of application development. But now I started to wonder if there is a way to combine the view showing the posts with the delete posts view. I thought that when the delete button was pressed, a window would appear on the page (eg using Bootstrap Modals) which would approve the deletion of the post. Delete View: class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post success_url = '/about' def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False View showing the post: class ShowView(generic.DetailView): model = Post template_name = 'blog/post_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.object.numbers_of_entries = self.object.numbers_of_entries + 1 self.object.save() return context If you need sth more just write! -
How to use Django packages with the same name?
There are two Django packages with the same option that I must add to the settings: Add "captcha" to the INSTALLED_APPS in your settings.py But it is not possible to add "captcha"to the settings two times because I will get the next error: django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: captcha So how can I use two packages with the same name in my Django project? PS: Please do not confuse "packages" and Django "apps". It described in official documentation about using apps with the same name, but there is nothing about packages. -
Python Django PWA paths
I was trying to make my site build with Django for python capable for mobile devices making a Progressive Web App. I have added to my base.html the following codes and it works, but when I click a link inside my page, it redirects to the page in Safari and not in the frame of the PWA. <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="apple-mobile-web-app-title" content="MyApp"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="default"> The other pages extends the base.html with the codes so I think, every file needs to have the codes on the but it doesn't work. Any clue of what this happens? -
Call prefetch_related_objects with arguments depend on an iterable
I have a list of objects to prefetch. And I need to use different order_by keys depend on the object. I wrote a function prefetch_iterable which return Prefetch object I call prefetch_related_objects function on iterable and pass prefetch_iterable() prefetch_related_objects(iterable, prefetch_iterable()) Can I somehow use different Prefetch objects for different elements of my list? -
how to fix reverse for logout not found in django python
i m customizing my admin page but getting this error Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name i have created admin directory creted the urls added base site and login templates. also created a view for logout in common directory class LogoutView(RedirectView): def dispatch(self, request, *args, **kwargs): auth_logout(self.request) return super(LogoutView, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): return HttpResponseRedirect(reverse('login')) rlpatterns = [ path('admin/', include(('jat_admin.urls', 'jat_admin'), namespace="admin")), path('admin/', admin.site.urls), path('common/', include(('common.urls', 'common'), namespace="common")), path("login/", views.LoginView.as_view(), name="login"), path("logout/", auth_views.LogoutView.as_view(), name="logout"), path('social-auth/', include('social_django.urls', namespace="social")), path("", views.HomeView.as_view(), name="home"), -
Using same methods in two models
i am customizing slug method for auto generating and i am using like this models.py class Category(TimeStamp): name = models.CharField(max_length=255) slug = models.SlugField(max_length=100, unique=True) def __str__(self): return self.name def _get_unique_slug(self): slug = slugify(self.name) unique_slug = slug num = 1 while Category.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): if not self.slug: self.slug = self._get_unique_slug() super().save(*args, **kwargs) I am using this _get_unique_slug method in another model. But I wander if there is beautiful way to right this in mixins. I mean without writing get_unique_slug for each model. How do I this? Thank you? -
how to return value from database using django and ajax
i have a dropdown list that display the data from the database. i need to make dynamic using jquery and ajax where it will hide some values based on the user input on another field. my question is how to hide the required option based on the returning ID. the error that i get is : Could not parse the remainder: '=="dep D"' from 'sources.source_name=="dep D"' views.py def getSource(request): sources = Source.objects.all() return render(request,'create_folder.html',{'sources':sources}) create_folder.html <div class="formSelect" id="mouresaleMasdarDiv"> <select id="mouresaleMasdar" name="gender" required> <option value="">-- soource--</option> {% for source in sources %} <option val="{{ source.source_name }}"> {{ source.source_name }} </option> {% endfor %} </select> </div> <script type="text/javascript"> $('#mouresaleMasdar option[value="{{sources.get(pk = 1)}}"]').hide() </script> It gives an error so how to make this value hidden based on the id. -
Right way to get CreateView with modelformset_factory with multi forms
I have a skill model whose instances belong to different categories (eventually around 10). I will use 2 categories to reduce the code. For example, 2 categories: frameworks: django, angular etc. language: python, java etc. I need the user to add all the information about himself on one page at once. I made two forms with different querysets that only give Skills instances belonging to a separate group and two Formset forms.py class SkillBaseCreateForm(forms.ModelForm): YEAR_CHOICES = [(r, r) for r in range(1, 11)] LAST_YEAR_CHOICES = [(r, r) for r in range(1980, datetime.datetime.now().year + 1)] year = forms.CharField( widget=forms.Select(choices=YEAR_CHOICES), ) last_year = forms.CharField(widget=forms.Select(choices=LAST_YEAR_CHOICES)) class Meta: model = Skill fields = ['technology', 'level', 'last_year', 'year'] class SkillCreatePLanguageForm(SkillBaseCreateForm): def __init__(self, *args, **kwargs): super(SkillCreatePLanguageForm, self).__init__(*args,**kwargs) self.fields['technology'].queryset = Technology.objects.filter(group_id='3') class SkillCreateFrameworkForm(SkillBaseCreateForm): def __init__(self, *args, **kwargs): super(SkillCreateFrameworkForm, self).__init__(*args,**kwargs) self.fields['technology'].queryset = Technology.objects.filter(group_id='2') formset SkillFrameworkFormSet = modelformset_factory(Skill, form=SkillCreateFrameworkForm, extra=4, max_num=4, can_delete=False) SkillPLanguageFormSet = modelformset_factory(Skill, form=SkillCreatePLanguageForm, extra=4, max_num=4, can_delete=False) views.py class SkillTestCreateView(AuthorizedMixin, CreateView): model = Skill form_class = SkillCreatePLanguageForm template_name = 'skill_create.html' def get_context_data(self, **kwargs): context = super(SkillTestCreateView, self).get_context_data(**kwargs) context['formset_framework'] = SkillFrameworkFormSet() context['formset_planguage'] = SkillPLanguageFormSet() return context def post(self, request, *args, **kwargs): self.object = None formset_framework = SkillFrameworkFormSet(request.POST) formset_planguage = SkillPLanguageFormSet(request.POST) if formset_framework.is_valid() and formset_planguage.is_valid(): return self.form_valid(formset_framework, formset_planguage) else: … -
Set model field set default to iterator
I'm trying to set reportNr field default to a number that iterates every time a report has been added. Is there any way to do this? In models.py: from django.db import models class RapportQuerySet(models.query.QuerySet): def active(self): return self.filter() class RapportManager(models.Manager): def get_queryset(self): return RapportQuerySet(self.model, using=self._db) def all(self): return self.get_queryset().active() class Rapport(models.Model): objects = RapportManager() reportNr = models.TextField(blank=True, default="?") avd = models.TextField(max_length=10, null=True, blank=True) ritningNr = models.TextField(max_length=20, null=True, blank=True) enhetsNr = models.TextField(max_length=40, null=True, blank=True) atgard = models.TextField(max_length=100,null=True, blank=True) namn = models.TextField(max_length=100,null=True, blank=True) anstNr = models.TextField(max_length=100,null=True, blank=True) date = models.DateTimeField() file = models.FileField(null=True, blank=True) def __str__(self): return self.reportNr -
Django APPEND_SLASH doesn't work properly
if i write example.com/example-example it is working. However if i write example.com/example-example/ it doesn't work APPEND_SLASH=True in settings.py path('<slug:slug>',post_detail,name="post_detail"), -
How can I troubleshoot issues with a circus socket?
Environment: NGINX Django Python Circus I have a website that was returning 504 errors on various pages. In the nginx error log I was getting the following errors: [error] 30117#0: *280231 upstream timed out (110: Connection timed out) while reading response header from upstream, client: xxx.xxx.xxx, server: www.website.com, request: "GET /en/path/page/ HTTP/1.1", upstream: "http://unix:/tmp/glp-circus.sock/en/path/page/", host: "www.website.com" I increased the execution timeout for the server and these pages appear to be loading, however they are very slow. According to the browser, the TTFB is over 2 minutes. Presumably the socket for GLP is still causing the issue. How can I go about troubleshooting sockets which are managed by Circus? I have checked that the GLP socket is active. https://circus.readthedocs.io/en/latest/