Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter queryset by full ManyToManyField occurrence?
I have a model with ManyToManyField class CustomUser(AbstractBaseUser, PermissionsMixin): skills = models.ManyToManyField('pro.Skill', related_name='users', blank=True) And search on it implemented by non-optimized way: def get_queryset(self): result = CustomUser.objects.all() if 'skills' in self.request.query_params: skill_ids = [int(sid) for sid in self.request.query_params.get('skills').split(',')] for skill_id in skill_ids: result = result.filter(skill_ownerships__skill_id=skill_id).distinct() return result.exclude(pk=self.request.user.pk) I need to get the same result by one query to the database. I need to find all users that have all skills, that are in skill_ids array. -
Generating a Fixed alpha + sequential numeric values in python
I am trying to workout a method where in my models would have a field that has a structure like: "ITEM1", where in the numeric part would increase sequentially and be unique eg: "ITEM2", "ITEM3", and so on. I am not sure how to achieve this. Please point me in the right direction. Thanks in Advance. -
How to make 2 for loop for these function in one
i have some problem how to merge 2 for loop in one, the function like this : for profile in profileContent['profiles']: profileName = profile['profileName'] for data_setting in profileContent['datasettings']: dataSettingName = data_setting['dataSettingName'] i have merge 2 for loop in one like this but still wrong, any idea for fix this? for profile,data_setting in profileContent['profiles']: profileName = profile['profileName'] dataSettingName = data_setting['dataSettingName'] -
How to see SQL query that caused error in Django migration?
I'm trying to run a data migration that deletes all rows in a table (say, MyModel). There is another table that points to that table (RelatedModel). The field in the RelatedModel that maps to MyModel has on_delete=models.SET_NULL. When I run the migration, however, I get: File "/usr/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 211, in _commit return self.connection.commit() IntegrityError: update or delete on table "MyModel" violates foreign key constraint "f2274d6f2be82bbff458f3e5487b1864" on table "RelatedModel" DETAIL: Key (uuid)=(ywKMUYx7G2RoK9vqqEWZPV) is still referenced from table "RelatedModel". I added a breakpoint in the migration and checked the SQL DELETE queries. I ran them interactively in the shell and they worked inside the transaction, but the migration still breaks when it tries to commit it. I can't see however which query exactly causes this error, so I don't know how to debug this. Any suggestions? Thanks. PS: I'm using Django 1.9.13, Python 2.7, PostgreSQL 10.4. -
Django: Add value in template_tag
I am using django-qr-code. Just adding {{ attendee.ticket_code }} generates {{ attendee.ticket_code }} what I didn't intend. Can you tell me how I get the value of {{ attendee.ticket_code }} in there? {% qr_from_text "{{ attendee.ticket_code }}" size="M" %} -
Render Django template on AJAX call
So far I have been rendering Django templates via forms as below: return render(request,'base/errorPage.html') I would like to know how to render a template using HttpResponseRedirect(reverse('base:errorPage')) when doing an AJAX call. My Django AJAX view function generally returns JSON data. AJAX code in VUE Axios : axios({ method: 'post', url: 'ajax/logout/', data: { }, responseType: 'json', }) .then ( function (response){ console.log('AJAX success'); // window.location = '';//i cant just use this to call a url coz i need to send input para }.bind(this)) .catch ( function (error){ console.log('ajaxLogout error=',error); }); Django view looks like : def ajaxLogout(request): # return HttpResponseRedirect(reverse('base:errorPage')) return JsonResponse ({"success":1} ) I want to call return HttpResponseRedirect(reverse('base:errorPage')) in my ajaxLogout python function. -
Access the uploaded image file from models.imagefield in Django
I want to process the image before saving it while uploading from models.ImageField(upload_to=None) but i could not be able to find the way to access the image. my code is below from django.db import models class Document(models.Model): document_name = models.CharField(max_length=200) img = models.ImageField(upload_to=None) some_func_value = Process_image(img) In the above code Process_image() function expects an image file in the form of numpy array in its argument to process but when i pass img i.e Process_image(img) it gives me an error that img is not a numpy array. I want to find a way to access the image to process it before saving it. Also what is returned by models.ImageField() in other words what is the type of img variable in above code? is there anyway to access an image from img variable -
django how to display a weeks data
Hi thanks for helping me I being doing some browsing on google and stack overflow, but documentation django and python I can hardly understand, how the they make code run I just can't figure out a way to display week data (table & chart) with two toggle button to toggle different weeks of 53 weeks in a year I had try using the week in Django template tags; https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#date but I get empty value instead; here example I did {{ value|date:"W" }} is there easily way to do this? I do not wish to use the weekarchiveview: https://docs.djangoproject.com/en/2.1/ref/class-based-views/generic-date-based/#weekarchiveview As I need to toggle between years,months and weeks on same page. Below are my codes this my code for views from django.shortcuts import render from django.views.generic import ListView, DetailView ,TemplateView from zigview.models import tank_system from django.utils import timezone from datetime import date, timedelta class EC(ListView): model = tank_system template_name = 'FrounterWeb/extends/EC.html' ordering = ['-datetime'] # sort dates in descending order def get_context_data(self, **kwargs): return {'tank': self.get_queryset()} This is my apps url codes from django.urls import path from . import views #function views from django.views.generic.base import TemplateView from django.contrib.auth.decorators import login_required, permission_required urlpatterns = [ path('',login_required(views.index.as_view()), name='index'), # views to call our … -
how to add thumbnail in the external url in django
I create an URL, but the image is not added so I want to add an image in that URL is http://13.126.39.143/en/health/shilpa-shetty-s-quick-fix-yoga-15-min-full-body-workout/ -
How to make Django REST User API with complex permissions
I want to make a Django REST User API with complex permissions as follows: GET Only Admin should be able to get all User data Logged in User should be to get himself and the names of other Users PUT Only Admin and Self should be able to PUT Except for is_staff and is_superuser only is_superuser should be able to change the status of a user Password changes by a User should require the old password if User is !is_staff password reset should be possible POST / DELETE Only Admin should be able POST/DELETE User User should be able to update his own Profile Unfortunately, I have no idea how to control the view or serializer to allow such permissions. Is there a template how I can exactly control the permissions? -
How do I make custom URLs using django?
Right now my urls.py file looks like so: re_path(r'^product-offers/(?P<product_item_id>[-\w]+)$', views.ProductOffersListView.as_view(), This takes a user to the page: www.shop.com/product/1234 However, is there any way to display the URL with the title (even if that URL doesn't change the dispatching). I want the URL to look like this: www.shop.com/product/1234/toy-truck The "toy-truck" part doesn't have to do anything, but it looks professional and would be nice to have. -
I could not createsuperuser for django
I want ti create super user I used For create super user command prompt When I write This Code Python manage.py createsuperuser I am taking this error Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\core\management__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 112, in handle username = self.get_input_data(self.username_field, input_msg, default_username) File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 193, in get_input_data raw_value = input(message) File "C:\Users\ysr\Desktop\Blog\venv\lib\encodings\cp437.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character '\u0131' in position 6: character maps to I am using pycharm2018.3.1x64 Please Help me Thanks for your Reply -
Heroku application error: An error occurred in the application and your page could not be served (django)
Hi i am newbee in heroku and stuck in process of deploying heroku application and i am not able to track where is the error so please help me out , using python django for application :- after running heroku log (fdttest) abhisek@jarvis:~/Desktop/testenvFDT/foodmood$ heroku logs 2018-12-12T19:49:28.330386+00:00 app[api]: Initial release by user raizadaabhi11@gmail.com 2018-12-12T19:49:28.330386+00:00 app[api]: Release v1 created by user raizadaabhi11@gmail.com 2018-12-12T19:49:30.426621+00:00 app[api]: Enable Logplex by user raizadaabhi11@gmail.com 2018-12-12T19:49:30.426621+00:00 app[api]: Release v2 created by user raizadaabhi11@gmail.com 2018-12-12T21:10:51.000000+00:00 app[api]: Build started by user raizadaabhi11@gmail.com 2018-12-12T21:10:52.000000+00:00 app[api]: Build failed -- check your build logs 2018-12-12T21:15:18.000000+00:00 app[api]: Build started by user raizadaabhi11@gmail.com 2018-12-12T21:15:19.000000+00:00 app[api]: Build failed -- check your build logs 2018-12-12T21:21:05.000000+00:00 app[api]: Build started by user raizadaabhi11@gmail.com 2018-12-12T21:21:22.000000+00:00 app[api]: Build failed -- check your build logs 2018-12-12T21:24:47.000000+00:00 app[api]: Build started by user raizadaabhi11@gmail.com 2018-12-12T21:25:21.659682+00:00 app[api]: Attach DATABASE (@ref:postgresql-flexible-33726) by user raizadaabhi11@ gmail.com The Procfile contain :- web: gunicorn foodmood.wsgi --log-file - -
how to send automate birthday email using cron job in django
I want to send automatically email to birthday boy. how to use cron jobs. i did not get any proper tutorial all over internet please help me out guys -
Where is context.base_url set?
I'm using behave and behave-django for my django project's testing. When I run print(context.base_url), I thought http://localhost:8000 was displayed. In fact, for example, http://localhost:40655 is displayed. The port number is always changing. Why? My environment: macOS(v10.14.1), Docker(v18.06.1-ce), Django(v2.1.4), behave(v1.2.6), behave-django(v1.1.0) I want to set the fixed port number. What should I do? -
How to get serialized API view data into another view?
What is the best way to get DRF API view data into another Django view? Currently I am just calling the view through requests module: response = requests.get('my_api_view') but is there a cleaner way? I can also just instantiate the API view class in another view, but this will give me unserialized objects. -
How to convert django default timezone to different format
time format "2018-12-13T05:20:06.427Z" django providing time xone in above format when i am fetching data from database using ORM query. in my model field is in below way. models.DateTimeField(auto_now=True, blank=True,null=True) HOw can i convert it into "24 feb 2018" like this -
Django Model Field with Secondary Field
I am trying to create a user sign up form in Django that allows for a primary field with an associated integer field. I need each user to be able to select a genre (for movies), and then the percentage (0-100) they like that genre. I have created the percentage as a separate model, but I need it to be associated with each genre per user. How can I associate each user's genres with a specific "like" percentage? Right now, I just have a box of the genre list, with no way to select the percentage like for each genre. #app/models.py class Length(models.Model): length = models.IntegerField(default="Default") def __str__(self): return str(self.length) class Genre(models.Model): title = models.CharField(max_length=40, help_text="Enter genre name", default="Default") like = models.ManyToManyField(Like, help_text='Genre like percent', default="1") def __str__(self): return self.title #users/models.py import stuff class User(AbstractUser): first_name = models.CharField(max_length = 30, blank = True) last_name = models.CharField(max_length = 30, blank = True) email = models.EmailField(unique = True) city = models.CharField(max_length = 30, blank = True, default='Default Town') state = models.CharField(max_length = 2, default='CA') summary = models.CharField(max_length=250, default='Default summary') genres = models.ManyToManyField(Genre, help_text='Select each genre.', default='default', related_name='genre_model') def __str__(self): return self.email #users/forms.py class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = User fields = ['username', … -
django site works locally not remote - returns page not found for any url path
I inherited a django site project which I have managed to setup and run locally. However when I attempt to deploy the django site remotely I am getting the following message while testing: Page not found (404) Request Method: GET Request URL: http://x.y.z.a:8000/ Raised by: core.views.HomeView Here is the following relevant information: Ubuntu 18.x running a virtual env (python 3.7.0) The message received. Again, not that I am getting the site to work fine locally. Let's ignore for now all the standard site checks (the site is pre wsgi / gunicorn / nginx etc. integration), so for the purposes of this test I am simply running python manage.py runserver 0.0.0.0:8000 - for now . Also note that port 8000 is open from this server (otherwise I would not get the debug view at all) From the screen it is referring to core.views.HomeView . in the "core" folder there us urls.py, which looks like this. from what I can see, there is nothing out of the ordinary here. So tracing it further, I can go to views.py Again, don't see anything out of the ordinary here, and the site does run locally. The home html page that is being referred to … -
Django: how to transform `path` url to DRF `router` url?
In a Django 2.1.4 project I had a working path-based urlpattern for a DRF view (that has a dynamic serialization if it matters): path('content/<str:slug>/<str:model>', views.ContentViewSet.as_view(), name='content') Then I decided to change my view to the viewset and now need to update the urlpattern. I tried: router = DefaultRouter(trailing_slash=False) router.register( # 'content/<str:slug>/<str:model>', # this didn't work either r'^content/(?P<slug>[-\w]+)/(?P<model>[\w]+)/$', views.ContentViewSet, base_name='content' ) urlpatterns += router.urls But got this error: '"%s" is not a valid regular expression: %s' % (regex, e) django.core.exceptions.ImproperlyConfigured: "^^content/(?P<slug>[-\w]+)/(?P<model>[\w]+)\.(?P<format>[a-z0-9]+)/?\.(?P<format>[a-z0-9]+)/?$" is not a valid regular expression: redefinition of group name 'format' as group 4; was group 3 at position 86 How to configure my urlpattern for router? -
Extending User model with one to one field- how to set user instance in view
I am trying to extend the user model using a one to one relationship to a UserProfile model. I added some boolean fields and in the view I am trying to use those fields as permissions. Here is my model: class UserProfile(models.Model): user = models.OneToOneField(User) FirstName = models.CharField(max_length=25) LastName = models.CharField(max_length=25) ProximityAccess = models.BooleanField(default=True) NewProxAccess = models.BooleanField(default=False) def __unicode__(self): return self.user.username and here is the view I am trying to use: @login_required def NewProx(request): if UserProfile.NewProxAccess: if request.method == 'POST': form = ProxForm(request.POST) if form.is_valid(): ProxPart_instance = form.save(commit=True) ProxPart_instance.save() return HttpResponseRedirect('/proximity') else: form = ProxForm() return render(request, 'app/NewProx.html', {'form': form}) else: raise PermissionDenied I don't get any error messages but it does not work as intended. I was hoping that if the user profile had NewProxAccess set to False it would raise the PermissionDenied but it doesn't. I have the admin module wired up and I can select or deselect the checkbox for that field but it has no effect. If I comment out the rest I can get it to show the Permission Denied error so it has to be in the view (I think). I think I am missing a line the establishes the logged in user as … -
get_channel_layer() outside browser
I have an API and I would like to call events that would update via websocket messages, as required. Think of something like a live filesystem, where someone may add a file either in the interface or by API and anyone viewing that folder would be able to view the update file paths. Here is what I'm currently doing in the web views: channel_layer = get_channel_layer() data = { "file": entity_data, "instanceId": None, "user": self.user_id, "type": "DELETE_FILE" } async_to_sync(channel_layer.group_send)( 'folder_event_' + str(parent_entity_access.entity_id), { "type": "folder_event_broadcast", "data": data } ) How would I do the same thing outside of the web application -- i.e., "get the channel layer" ? -
Filtering OrganizationUser's by Organization in Django-Organizations
There is a relatively similar thread on this topic, but I can't seem to figure out how to translate it to my situation. I have a roster that I need to only display the organizationusers within the same organization of the viewer. I have a webapp that I am developing that is used to manage volunteers in an organization. I'm still new to backend development so I'm having trouble problem solving. This is the code for the table view using Django_Tables2 package: #tables.py class VolunteerTable(tables.Table): class Meta: model = OrganizationUser # views.py def VolunteerRoster(request): table = tables.VolunteerTable(OrganizationUser.objects.all()) return render(request, 'staff/roster.html', {'table': table}) I'm trying to figure out how to either convert the view to a class-based view so I can use the OrganizationMixin and the SingleTableView in Django_Tables2's documentation. I was thinking about something like this based on the other threads explanation class VolunteerRoster(SingleTableView, OrganizationMixin): table_class = VolunteerTable queryset = OrganizationUser.objects.all() template_name = "staff_roster.html" def get_queryset(self): return self.queryset.filter(organization=self.get_organization()) When I try this I get: "TypeError: init() takes 1 positional argument but 2 were given" As I said, I'm still new to django so I'm not really sure what to fix in this instance. -
Django - Get name of model object by iterating through class
I'm new to Python (and pretty inexperienced at programming in general), but I have an issue I can't for the life of me figure out. I'm trying to pre-populate a field in my database with the name of an instance from another model/class in my database. The model with the field I want to pre-populate is an "instance" of the model instance from which I'm trying to grab the name, and has a foreign key to that instance. Goal: 1) User selects the parent of the object by assigning the foreign key to the parent 2) A function grabs the name of the parent instance matching the foreign key the user selected. 3) the result from that function is used as the default value for the field. Here's the code: class Injury(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular injury') name = models.CharField(max_length=200, help_text='Enter an injury or complication (e.g. respiratory failure)') description = models.TextField(max_length=1000, blank=True, help_text='Describe the injury') time_to_onset = models.PositiveIntegerField(blank=True, validators=[MaxValueValidator(10000)], help_text='Enter expected time from trigger until injury/complication onset') findings = models.TextField(max_length=1000, blank=True, help_text='Enter the signs and symptoms of the injury or complication') vitals_trends = models.TextField(max_length=1000, blank=True, help_text='Enter the vitals changes due to the injury') class Meta: … -
What is the best practice in structuring templates in your Django project?
I know there's a lot of questions regarding best practices of how to structure an entire Django project but i cannot find a concrete explanation on how to structure templates for a Django project. Obviously, I've just started learning Python/Django and i'm quite confused why most of the tutorials/examples i found, the directory name under templates directory is always the same as the its applications directory name. For example: gazette/ __init__.py models.py views.py static/ ... templates/ gazette/ __base.html __l_single_col.html __l_right_sidebar.html __l_left_sidebar.html _article_full.html _article_summary.html _author_list.html _author_name.html _category_list.html _navigation.html _tag_list.html article_detail.html article_list.html author_list.html category_list.html tag_list.html this actually came from a blog: https://oncampus.oberlin.edu/webteam/2012/09/architecture-django-templates In the application structure above, the application gazette/ have templates/ directory under it. In turn, under templates/, there's a single directory called gazette/, which is the same name as the application where it resides. This folder then contains all the actual html template files. Question: Why can't we just directly put all the html template files under templates/ directory? I would understand the logic of the structure if there are several directories under templates but i never found a single example from any tutorials in YouTube or blogs. If you could explain the principle behind it and direct me to …