Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set active tab using crispy form?
I have the following code snippet to show the tabs using crispy form in a modelform. Is it possible to set the active tab when the page loads? I don't know where to put the css_class='Active". Thanks in advance self.helper.layout = Layout( common_layout, TabHolder( Tab( 'Tab1', Field('name', readonly=True), Field('age', readonly=True), ), Tab( 'class', Field('grade 1'), ), ) ) -
Django ImportError for valid import
I think this is best explained with a little code. Be aware the slightly weird relationships between the data is a hack to get inlines working with many-to-many relationships. The app "data" has the following models.py: from crawler.models import CrawlJoin class Website(models.Model): hack = models.ForeignKey(CrawlJoin, null=True, blank=True, editable=False) The app "crawler" has the following models.py: from data.models import Website class CrawlJoin(models.Model): pass class Crawl(models.Model): websites = models.ManyToManyField(CrawlJoin, through='Website') If I try to migrate either crawler or data, I get the following error: ImportError: cannot import name 'CrawlJoin' Do you know how I can resolve this issue? As far as I can tell, I should not be getting this error... Thank you. -
Django - multiple custom filter arguments
I can't figure out how to send multiple arguments into custom template filter. The problem is that I use template variables as an arguments. CUSTOM TEMPLATE FILTER @register.filter def is_scheduled(product_id,dayhour): day,hour = dayhour.split(',') return Product.objects.get(id=product_id).is_scheduled(day,hour) NORMAL USE {% if product.id|is_scheduled:"7,22" %}...{% endif %} The line above would work correctly like I put two arguments - 7 and 22 into the filter. The problem is that I want to put variables instead of plain text/string as an argument. In my template: {% with day=forloop.counter|add:"-2" hour=forloop.parentloop.counter|add:"-2" %} Now, I want to use {{ day }} and {{ hour }} as an arguments. I tried for example: {% if product.id|is_scheduled:"{{ day }},{{ hour }}" %}...{% endif %} But this raises: Exception Value: invalid literal for int() with base 10: '{{ day }}' Do you have any ideas? -
Django display items from ManyToMany field
I currently have two models: class Artist(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Track(models.Model): title = models.CharField(max_length=255) artist = models.ManyToManyField('Artist') def __str__(self): return '%s - %s' % (self.title, [artist.name for artist in self.artist.all()]) Only this will display the following SomeSongTitle - ['SomeArtistName']. I understand it does this because it is many to many, but is there some way to display only the string for this, like the __str__ would normally function in the Artist model? -
NoReverseMatch at /category/clothes/ Django class based views
I have a django project that is close to an e-commerce wesite in terms of functionality. There are four pages linked to one another. First page displays Categories, 2nd Subcategories, 3rd Product list and 4th Product detail and I'm using slugs to navigate. ERROR Reverse for 'product-list' with arguments '('', '')' and keyword arguments '{}' not found. 1 pattern(s) tried: ['category/(?P<category_slug>[-\\w]+)/(?P<subcategory_slug>[-\\w]+)/$'] Category to Subcategory linking code on the category_list.html is <a href="{% url 'products-app:sub-category' category.category_slug %}">{{ category.name }}</a> and on the views.py class CategoryListView(ListView): models = Category template_name = 'products/category_list.html' context_object_name = "Category list" def get_queryset(self): """ Returns all categories. """ return Category.objects.get_queryset().all() and urls.py app_name = 'products' urlpatterns = [ url(r'^$', CategoryListView.as_view(), name='categories'), url(r'^(?P<category_slug>[-\w]+)/$', SubcategoryListView.as_view(), name='sub-category'), url(r'^(?P<category_slug>[-\w]+)/(?P<subcategory_slug>[-\w]+)/$', ProductListView.as_view(), name='product-list'), url(r'^(?P<category_slug>[-\w]+)/(?P<subcategory_slug>[-\w]+)/(?P<pk>\d+)/$', ProductDetailView.as_view(), name='product-detail'),] The problem is linking subcategory_list.html to product_list. Since I need a category_slug and subcategory_slug to be pass to <a href="{% url 'products-app:product-list' category_slug subcategory_slug %}">{{ object.name }}</a>. I don't know how to implement this logic to using cbv. I want to pass category_slug since it is from a Category model and querying from Subcategory model. views.py class SubcategoryListView(ListView): """ Browse all products in the sub-catalogue. """ model = Subcategory template_name = 'products/subcategory_list.html' context_object_name = "Sub-Category list" category_model … -
@import in .css in a Django App
So I am working on a Django app, and I am trying to use an HTML5 UP template with it. I have everything in the static folders, but the css with the template isn't showing up quite right. The top of the .css file has an @import statement, and the view doesn't seem to be changing if I change that line, so I think that's where the problem is. The default in the template was this: @import url("https://fonts.googleapis.com/css?family=Ubuntu+Condensed"); And so far I have tried both this: @import url("assets/css/Ubuntu_Condensed.css"); and this: @import url("Ubuntu_Condensed.css");, but nothing makes any difference. Any help on this would be appreciated! Thanks! -
How to view my local database name in Django
I am trying to find what my local database name is, as it isn't directly stated in my settings file. This is what I have currently listed. DATABASES = { 'default': dj_database_url.config( default='sqlite:////{0}'.format(os.path.join(BASE_DIR, 'db.sqlite3')) ) } I don't want to change anything because I am a bit freaked out it will change anything I already have. Any way to do this through something like the shell? -
Poor performance of db. inserts using django-mssql
I designed data warehousing application, but I struggle with poor performance when fetching data from the source and saving them to db. - only approximately 150 kB/s. Because of the limitations imposed by the customer, I am forced to use Django on 64bit Win machine and save data to MS SQL Express (exact versions below). I am using django-mssql (1.7) backend. Original data are stored in .dbf file (Visual FoxPro), dbfread returns each row from a file as Python dict (this is not the issue, tested by running just reader discarding data). This dictionary is then checked for data quality (function sanitize_value_for_db() below), data are copied to Django data model (attributes of the object populated; tables are wide, hence each table/object has about 100 columns/attributes) and objects are saved to db. using Django objects.bulk_create(). I run the code through profiler using cProfile and pstats modules. Results are below. I see that most of the time is spent in PyWin. But I have no clue if there is something I can do. Any hints or opinions will be greatly appreciated. Thanks. Configuration: Xeon E5-2403 v2 @ 1,8 GHz, 30 GB RAM Windows Server 2012 R2 (64bit) MS SQL Express 64bit, v … -
Using extra_data from python-social-auth in Django template
I am using python-social-auth to log in my own web application from LinkedIn. I successfully logged in and redirect to my home page. The next step is to utilize the extra data (i.e. UserSocialAuth.extra_data). Could anyone give a example about how to access the extra data in either Django templates or Django views? This is the settings I had. SOCIAL_AUTH_LOGIN_URL = '' SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'social.pipeline.user.create_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details' ) SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_basicprofile', 'r_emailaddress', 'rw_company_admin', 'w_share'] SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = ['first-name', 'last-name', 'email-address', 'headline'] SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA = [('id', 'id'), ('first-name', 'first_name'), ('last-name', 'last_name'), ('email-address', 'email_address'), ('headline', 'headline'), ('industry', 'industry')] What I am going to do is like: <html><body>Here we go! {{ user.first_name }} {{ user.last_name }} {{ user.email }} {{ user.extra_data.headline }}</body></html> Any comments will be highly appreciated! -
Altering Django forms based on in browser button clicks
I am making a website that requires a user to upload a clothes item via inputting necessary data on a form. I currently have a model class: class Clothes_Item(models.Model): #definitions of multiple fields (user, description, gender of item, type of clothing, etc.) However, based on what the gender of this clothing item is, I would like to display a set of choices for "types of clothing" which the user can choose from. For example, for female clothing items, I need to have an extra clothing type option for "Dress". My goal is to have three buttons (male, female, and unisex) on the webpage that, when clicked, display a clothes form with all data the same, except for the different options for the "type of clothing" field. The gender field of the Clothes_Item model should become filled in when a user clicks one of the buttons. I have tried multiple approaches but all of them seemed inefficient and clunky. The only way I was able to make it work was by creating separate models and forms for male, female, and unisex clothes items and loading each of these forms into my template and displaying only the appropriate one. I know there … -
rest_framework_swagger 2.1 configuration: how do you pass the api key?
The problem I'm attempting to update Swagger for my Django app which uses Token-based authentication with Django Rest Framework. I keep getting the following error when I visit the docs page: 401 : {"detail":"Authentication credentials were not provided."} http://localhost:7000/api/docs/?format=openapi Clearly, it's not passing the API key in the header. My problem is that I don't know how to supply it an API Key through settings/environment variables/etc. Does someone know of a representative example, or can someone tell me what's wrong? What I've done so far I've read the documentation for Swagger I've attempted to add api_key to the settings in different ways, following the basic layout of the documentation: SWAGGER_SETTINGS = { 'LOGIN_URL': 'rest_framework:login', 'LOGOUT_URL': 'rest_framework:logout', 'USE_SESSION_AUTH': False, 'SECURITY_DEFINITIONS': { 'basic': {'type': 'apiKey'}, 'api_key': { 'type': 'apiKey', 'in': 'header', 'name': 'Authorization', }, }, } I've tried putting "api_key": "<the api key>" under SWAGGER_SETTINGS and under SECURITY_DEFINITIONS, but it has't worked. I've read the python source code for Swagger, but it doesn't directly handle tokens. It does pass the securityDefinitions to an OpenAPICodec, which returns a JSON dump of a swagger object created from those securityDefinitions. I've read some of the OpenAPI Specifications on the securityDefinitions object. In the documentation, it … -
How does DRF know a simple POST request should call create()?
I think this is best explained with a code example. Angular makes a POST request like this: $http.post('/api/accounts/', { username: username, password: password, email: email } This gets picked up by Django in urls.py: router = routers.SimpleRouter() router.register(r'accounts', AccountViewSet) urlpatterns = [ url(r'^api/', include(router.urls)), ] Here's AccountViewSet: class AccountViewSet(viewsets.ModelViewSet): serializer_class = AccountSerializer queryset = Account.objects.all() lookup_field = 'username' def create(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return Response( serializer.validated_data, status=status.HTTP_201_CREATED ) And here's the serializer: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account def create(self, validated_data): return Account.objects.create_user(**validated_data) At no point in this code can I see something which translates to "if Angular sends a POST request to api/accounts/ which has a username, password and e-mail address, go ahead and create an account". So my question is this: How does DRF know to call AccountViewSet.create(), and where exactly is AccountSerializer.create() getting called? There seems to be a lot of magic happening here. Thanks for your help. -
Detect change in apps and user who made changes by a separate app Django.
I'm trying to create an app, say activitylogapp in the project that detects if in another app say Employeeapp some models are changed/updated and keep a log. I don't want touch Employeeapp. I can access changes by using signals in the models.py of activitylodapp. By this: from django.db.models.signals import post_save from anotherapp.models import Employee from django.dispatch import receiver @receiver(post_save, sender=Employee) def save_handler(sender, instance, created, **kswargs): "Things I want to do" The problem is I also want to access which user made these changes, like request.user.username that is used in views.py. Is it possible without explicitly injecting request object from view to activitylog app? -
AbstractClass ForeignKey reference to AbstractClass
I am building a compliance management system where I have the following requirements for most models in my project: My Requirements Users with certain roles can change fields, but this has to lead to a new "version" with a draft status After approval through certain other roles (i.e. managers) this version of the model has to be published History has to be accessible for all roles Current Situation Because available django-apps did not meet all these requirements I created to following constuct: Every model (e.g. Policy) has one Master and one Detail model. The Master model has the following fields: id deleted currentActiveDetail (ForeignKey) The Detail model has the following fields: id majorVersion minorVersion author masterModel (ForeignKey to Master) user (ForeignKey to auth.User) lifecycleStatus (Choice, i.e. 'Draft', 'Waiting Approval', 'Approved', 'Obsolete') a lot of content fields (e.g. Description, Text,...) a lot of methods Challenges/Questions Because I have a lot of such use cases I want to make a MasterAbstractClass and a DetailAbstractClass but I can't find a solution to the following challanges: How to "reserve" the ForeignKey fields in the abstract class (I know that I can't define them because there is no table in the database). I thought if … -
Django model extending Default User model (one-to-one field), how to create reg form for all combined model fields in HTML Django Templating?
This is my user profile model: class student(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) state = models.CharField(max_length=21, null=True, blank=True, choices=in_states.STATE_CHOICES) city = models.CharField(max_length=21, null=True, blank=True) date_joined = models.DateTimeField(default=timezone.now) educational_role = models.CharField(max_length=39, choices=EDUCATIONAL_ROLE) institute = models.ForeignKey(educational_institute, null=True, blank=True) language = models.CharField(max_length=8, choices=LANGUAGES) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: student.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() When I created form class for student and use that to create a View class extending FormView class in my Views passing the form context to HTML template like this: forms.py : class RegistrationForm(forms.ModelForm): class Meta: model = student fields = ['user', 'state', 'city', 'educational_role', 'institute', 'language'] views.py : `class Register(FormView): template_name = 'searcher/register.html' form_class = RegistrationForm def get_context_data(self, **kwargs): context = super(Register, self).get_context_data(**kwargs) context['applink'] = applink context['forumlink'] = forumlink return context` So how do I need to modify this so that the registration form asks for username, firstname, email of User model and also the fields added by student model and having option for creating a new educational_institute if it doesn't exist already? -
Django Queryset running two times
Hi Why Django calling this query set two times ? class AccountListView(ListCreateAPIView): serializer_class = AccountSerializer def get_queryset(self): print 'get query set' return Accounts.objects.filter(user=self.request.user) -
Storing weekly/daily scheduling in Django database
In my project, user can set for each of their items schedule for action. This action can be done for example once a week at 1am, every day at 2am or every Monday and Wednesday at 3pm, 6pm and 9am. So the form could look like: To spare resources, the minimal time is hour so I can run celery task which every hour checks all schedules and find out if it have to do an action now. I'm trying to figure out what is the best way to store such schedule in the database and how to make such a model. The first thing I was going to do was to store something like celery cron tab for each product in string format - 'x x x x x' - for example "hour='3,17,22', day_of_week='thu,fri'". But I think that it's bad because I would have to parse each string each hour which is very time-consuming. Finally I did model with 7 columns - days and 24 columns hours. There are two problems - it isn't probably the best way to store such schedule and the second thing is that every (True) day would have set the same hours which I don't … -
django inheritance accessing all children in parent class
Consider I have a parent class Parent with attributes: att1, att2. It has two children Child1 with attributes: att3, att4 and Child2 with attributes: att5, att5 Normally, I create Child1 or Child2 objects (say through admin interface) and they are added to Parent table. Is it possible to create a Parent object in a following way: In admin interface I get to choose for Parent which child I want to create: if I select Child1, it's attributes will be appended in admin interface, if I choose Child2 it's attributes will be appended along with original att1, att2 of Parent? When I create such a Parent, corresponding child will also be created. something similar I implemented (it's altogether a different thing, however the behavior I am looking for is similar): https://github.com/goinnn/django-multiselectfield Why I am trying this: In my parent table it is hard to tell, to which child a specific row belongs. -
Slow Raspberry pi 3 wireless (wifi) adhoc network
I have 2 raspberry pi-3. They communicate wirelessly via a wifi powered adhoc network. One of which is a Django server that can serve up to 15 requests per second. But, unfortunately, my client raspberry pi can send and receive only 3 (without overclocking) to 4 (with overclocking) requests per second. Following is the python code which runs on the client raspberry pi and sends requests, import requests while True: r = requests.get('http://192.168.1.1:8000/g2/') print r.content` It would be great of if somebody could help me increase the client side request rate -
how to merge two annotated querysets into one result
Model: class Foo(models.model): name = models.CharField(max_length = 50, blank = True, unique = True) class Bar1(models.Model): foo = models.ForeignKey('Foo') value = models.DecimalField(max_digits=10,decimal_places=2) class Bar2(models.Model): foo = models.ForeignKey('Foo') value = models.DecimalField(max_digits=10,decimal_places=2) Clasess Bar1 and Bar2 are unrelated, so I can't do it as one class what would solve the problem. But this is only example to show the problem as pure as possible. first = Foo.objects.all().annotate(Sum("bar1__value")) second = Foo.objects.all().annotate(Sum("bar2__value")) each of this querysets contains correct values. I can't merge it into: both = Foo.objects.all().annotate(Sum("bar1__value")).annotate(Sum("bar2__value")) Because the sum value multiplicates - this is unfortunately expected behaviour - because of JOINS And now the problem - how to merge/join first and second to get the both? Example: Bar 1: foo | value -------------- A | 10 B | 20 B | 20 Bar 2: foo | value -------------- A | -0.10 A | -0.10 B | -0.20 expected result: foo | bar1__value__sum | bar1__value__sum --------------------------------- A | 10 | -0.20 B | 40 | -0.10 I couldn't use itertools.chains because the result is: foo | bar1__value__sum | bar1__value__sum --------------------------------- A | null | -0.20 B | null | -0.10 A | 10 | null B | 40 | null -
keep record of post in a social network feed
In a project I'm trying to make a simple social network feed. I get the latest posts and append it to the feed. Each post will have a Like and Share button. How do I keep a record of these posts? Eg: Someone clicks Like button of a particular post. How do I know in back-end which post was it? By giving dynamic IDs to post? I understand this question is broad. But still would be grateful if you can help. thanks -
Django celery: class-based task doesn't work
tasks.py from celery import Task class SimpleTask(Task): def run(self): print("run") Execute python manage.py shell In [3]: from products.tasks import SimpleTask In [4]: task = SimpleTask() In [6]: task.run() run Successfully work and no error logs come out in worker server. Howerver, In [7]: task.delay() Out[7]: <AsyncResult: a2e90b17-2af9-49b4-82df-562955beaf69> And worker server log shows errors: [2016-11-05 18:44:03,171: ERROR/MainProcess] Received unregistered task of type None. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: b'[[], {}, {"callbacks": null, "chord": null, "errbacks": null, "chain": null}]' (77b) Traceback (most recent call last): File "/Users/Chois/.pyenv/versions/3.5.1/envs/spacegraphy/lib/python3.5/site-packages/celery/worker/consumer/consumer.py", line 549, in on_task_received strategy = strategies[type_] KeyError I don't see why this happens. If I created function-based task using @shared_task it successfully works. But only class-based Task doesn't work. Need helps, Thanks. -
django - how can query by date
i need to query models by some date. dates passed to reservation_f by url. but return me this error: Reverse for 'reserve' with arguments '()' and keyword arguments '{u'date': datetime.date(2016, 11, 4)}' not found. 1 pattern(s) tried: ['reserve/(?P<date>)/$'] models.py: class Food(models.Model): food_name = models.CharField(verbose_name="Food Name", max_length=50) serve_date = models.DateField(verbose_name="Serve Date") price = models.CharField(verbose_name="Food Price", max_length=50) views.py: def reservation_f(request, date): food = Food.objects.filter(serve_date = date) return render(request, 'food.html', {'food':food}) urls.py: from reservation import views as reservation_views urlpatterns = [ url(r'^$', reservation_views.index, name='index'), url(r'^reserve/(?P<date>)/$', reservation_views.reservation_f, name='reserve') ] template.html: <a href="{% url 'reserve' date=date.serve_date %}"> {{date.serve_date }} </a> -
Django not launching browser
I tried to make a web app following this tutorial https://youtu.be/WG3pGmoo8nE In video at 2:05 when he runs the app it works... However when i run the app, browser doesn't launch. any idea why? -
not able to save one shipping address and one billing address in Django
In My eCommerce project i am not able to save billing and shipping address Boolean Field correctly in admin models.I will explain it with screen shot First Step: I can Add Multiple Address in Admin for one customer, So here i have address A and address B When i Check on Billing address form address A and Shipping address from address B it is saved successfully condition 1 screen shot def check_billing_shipping(self): if self.billing_address: temp = Address.objects.filter(billing_address=True, customer=self.customer) for key in temp: if key.billing_address: key.billing_address = False key.save() if self.shipping_address: temp = Address.objects.filter(shipping_address=True, customer=self.customer) for key in temp: if (key.shipping_address): key.shipping_address = False key.save() super(Address, self).save() def save(self, *args, **kwargs): super(Address, self).save(*args, **kwargs) self.check_billing_shipping() Same way if interchanged it i.e When i Check on Shipping address form address A and Billing address from address B and then save it discards all checked from Address A after save screen shot and code for save is as we know shipping and billing address is most impoertant in ecommerce so i need a help here also if u dont get a question please ask again i will expalin it in better way