Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I get a param inside an URL in django admin?
I use django admin and want to access the object id in an URL like this: http://localhost:8000/polls/platform/837/change class PlatformAdmin(admin.ModelAdmin): def get_queryset(self, request): print(request.??) So what should be returned is the 837 -
How to validate Stripe in django-form-tools?
I've a 5 form wizard, with the last step taking credit card details using Stripe. I need to validate the Stripe details and return the user to the form should they generate payment card error. I am doing something like this def done(self, form_list, form_dict, **kwargs): stripe.api_key = settings.STRIPE_SECRET_KEY .... try: card_token = Card.create_token ( number=self.request.POST['checkout-cardNumber'], exp_month = int(self.request.POST['checkout-expiryDate'].split('/')[0]), exp_year = int(self.request.POST['checkout-expiryDate'].split('/')[1]), cvc = self.request.POST['checkout-cvv'], ) except Exception as e: return HttpResponseRedirect(self.request.META.get('HTTP_REFERER')) ... I know this isn't returning an error message but the bigger problem is because I'm in the done method form-tools has cleared the form wizard and it returns me to a blank form at the start of the process. With that in mind I started adding to the clean method of the form. stripe.api_key = settings.STRIPE_SECRET_KEY try: card_token = Card.create_token ( number=cleaned_data['cardNumber'], exp_month = int(cleaned_data['expiryDate'].split('/')[0]), exp_year = int(cleaned_data['expiryDate'].split('/')[1]), cvc = cleaned_data['cvv'], ) except Exception as e: if "Your card number is incorrect." in str(e): self.add_error('cardNumber', "Your card number is incorrect.") else: self.add_error('cardNumber', e) This works great for this example but the next step is to process the card using something like: try: djstripe_customer = Customer.objects.get(subscriber=self.request.user) customer = stripe.Customer.retrieve(djstripe_customer.id) customer.sources.create(source=card_token) except: #deal with exception pass The problem here … -
for i, middleware in enumerate(settings.MIDDLEWARE): TypeError: 'NoneType' object is not iterable
I got this error when i try to run python manage.py runserver or any other python manage.py * commands in command line. but when i tried python manage.py shell it connected without error and gets data from database. error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fa03b7386a8> Traceback (most recent call last): File "/home/tornike/apps/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/tornike/apps/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/home/tornike/apps/env/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/tornike/apps/env/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/tornike/apps/env/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/tornike/apps/env/lib/python3.6/site-packages/debug_toolbar/apps.py", line 25, in check_middleware for i, middleware in enumerate(settings.MIDDLEWARE): TypeError: 'NoneType' object is not iterable MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware' ) -
Django ORM get instance with unique ManyToMany [duplicate]
This question already has an answer here: Django queryset get exact manytomany lookup [duplicate] 1 answer Here is my issue: I want to grab the model instance that has a unique set of ManyToMany instances. For example, I have 3 models (one is a joint table): class Itinerary(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class FlightLeg(models.Model): flight = models.ForeignKey('flights.Flight', on_delete=models.CASCADE, related_name='flight_legs') itinerary = models.ForeignKey('itineraries.Itinerary', on_delete=models.CASCADE, related_name='flight_legs') class Flight(models.Model): itineraries = models.ManyToManyField( 'itineraries.Itinerary', through='itineraries.FlightLeg', related_name='flights' ) I'd like to query the Itinerary instance that has a particular list of flights. For example, let's say I have an Itinerary that has 3 flights with id 1,2,3 respectively. Let's say I have another Itinerary with ids 2,3. In both these cases, I'd like to query the itinerary that has a unique set of flights. So if I query an itinerary with flight id 1 and 2 it should not return the one with flight ids 1,2,3. Right now I've tried this but it obviously doesn't work: flights = [<Flight: B6 987>, <Flight: AM 401>, <Flight: AM 19>] query = reduce(and_, (Q(flight_legs__flight=flight) for flight in flights)) itinerary = Itinerary.objects.filter(query) I only want to return the Itinerary that has these 3 flights and nothing else. … -
How to modify a many-to-many collection using django rest framework
I am trying to create an endpoint where, having a User entity, I can add / remove existing Group entities to user.groups many-to-many field. But when I try to do it, django-rest-framework tries to create new group objects instead of finding existing ones. I have defined two serializers where UserSerializer has a nested GroupSerializer: class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ['id', 'name'] class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'groups'] groups = GroupSerializer(many=True) def update(self, instance, validated_data): data = validated_data.copy() groups = data.pop('groups', []) for key, val in data.items(): setattr(instance, key, val) instance.groups.clear() for group in groups: instance.groups.add(group) return instance def create(self, validated_data): data = validated_data.copy() groups = data.pop('groups', []) instance = self.Meta.model.objects.create(**data) for group in groups: instance.groups.add(group) return instance When I send a JSON: { "id": 6, "username": "user5@example.com", "email": "user5@example.com", "groups": [ { "id": 1, "name": "AAA" } ] } I expect serializer to find the Group with given id and add it to User. But instead, it tries to create a new user group and fails with duplicate key error: { "groups": [ { "name": [ "group with this name already exists." ] } ] } I searched over … -
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?