Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
while installing django framework getting this error, ERROR: Command errored out with exit status 1:
Installing collected packages: MySQL-python, psycopg2, websocket-client, pathlib, boto, zc.lockfile, django-framework Running setup.py install for MySQL-python ... error ERROR: Command errored out with exit status 1: command: 'c:\users\gowth\appdata\local\programs\python\python38\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\gowth\AppData\Local\Temp\pip-install-i8agy_6_\mysql-python\setup.py'"'"'; file='"'"'C:\Users\gowth\AppData\Local\Temp\pip-install-i8agy_6_\mysql-python\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\gowth\AppData\Local\Temp\pip-record-_ovoppb0\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\gowth\appdata\local\programs\python\python38\Include\MySQL-python' -
Rendering another view on POST method
I want to post some data to my Index View and then render the Results page with that information. However, when i return the Results View on my post method, nothing happens (the Index View doesn't redirect to the 'results_page.html' template) class IndexPageView(View): def get(self, request, *args, **kwargs): # Something return render(request, r'index_page.html', context) def post(self, request, *args, **kwargs): # Doing something with the POST data return ResultsView(request, results = results) def ResultsView(request, **kwargs): context = {} if 'results' in kwargs: context['results'] = kwargs['results'] print('im here') return render(request, r'results_page.html', context) The status code of the post request is ok and the print message shows up on the terminal. What am i doing wrong here. edit. Forgot to add that ResultsView works fine when it's called through the urls.py -
django auth user (sign-up) with group of permission
How do I do, if i have django auth user sign-up that if the user signs up, their created account will automatically be registered in the "client" group of permission this is my views.py class SignUpView(CreateView): form_class = SignUpForm group = Group.objects.get(name='client') user.groups.add(group) ==> it didnt work success_url = reverse_lazy('loginpage') template_name = 'customAdmin/signup.html' forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, help_text='Optional') last_name = forms.CharField(max_length=30, help_text='Optional') email = forms.EmailField(max_length=254, required=False, help_text='Optional') class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', ] -
Django inline has no ForeignKey but has one?
I want to try to add a ListField increasible on django admin. I discover I can do that with inlines, so I goes to the doc to find this code : models.py from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=100) admin.py class BookInline(admin.TabularInline): model = Book class AuthorAdmin(admin.ModelAdmin): inlines = [ BookInline, ] I simply copy this code to see how it render on Django admin page. But the following error appear : <class 'users.admin.BookInline'>: (admin.E202) 'users.Book' has no ForeignKey to 'users.Book'. I don't understand why because Book as a ForeignKey. Am I missing something ? Thx -
django.template.exceptions.TemplateDoesNotExist: base.html
I am creating Django User Registration Authentication – SignUpView, I dont know why i cant detect the base.html in my html file this is the full traceback Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response response = response.render() File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py", line 106, in render self.content = self.rendered_content File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py", line 83, in rendered_content content = template.render(context, self._request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\backends\django.py", line 63, in render reraise(exc, self.backend) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\backends\django.py", line 84, in reraise raise new from exc django.template.exceptions.TemplateDoesNotExist: base.html [10/Aug/2020 18:44:15] "GET /SignUpView/ HTTP/1.1" 500 126471 this is my file tree this is my views.py class SignUpView(CreateView): form_class = SignUpForm success_url = reverse_lazy('loginpage') template_name = 'customAdmin/signup.html' this is my urls.py from customAdmin.views import SignUpView urlpatterns = [ path('admin/', admin.site.urls), path('SignUpView/', SignUpView.as_view(), name='SignUpView'), path('', customAdmin.views.Homepage, name='Homepage'), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) this is my html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Sign-Up</title> </head> <body> {% extends 'base.html' %} {% block title %}Sign Page{% endblock title %} {% block content %} <h2>Sign Page</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Register</button> <br><br> <a href="{% url 'home' %}">Home</a> </form> … -
javascript null doesn't convert to None
@parser_classes([MultiPartParser, FormParser]) @api_view(['POST', ]) def product_list(request): print(request.POST.get('key')) print(request.data.get('key')) print(request.FILES) When I am sending form data with value of key=null it displays null as string but didn't convert to None what should I do. The work around that I have to do is something like if request.data.get('key', None) in ['null', None]: #then do something But this doesn't seem to be a clean way of doing this. So what should I do? I expected that django or drf will automatically convert null to None. -
How can I use Erlang in a Django project?
I am planning to develop a social platform for my university based on fully Django. But in terms of chatting functionality I am willing to do that by using Erlang (I'm not that much skilled in Erlang right now). How can I connect this two languages? -
Django: Can I use a subprocess w/ docker-compose inside a custom command?
I created a custom command in django and I want to use a docker-compose command in it. I use a subprocess as follow: class Command(BaseCommand): def handle(self, *args, **options): data = open_file() os.environ['DATA'] = data command_name = ["docker-compose ", "-f", "docker-compose.admin.yml", "up"] popen = subprocess.Popen(command_name, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) return popen when I do it I get a FileNotFoundError: FileNotFoundError: [Errno 2] No such file or directory: 'docker-compose ': 'docker-compose Is it even possible to use docker-compose inside of a command ? It feels like I am missing something. Thank you ! -
Can a per-query cache with pagination ever work in real life scenarios?
I started using the Django built in caching mechanism, at individual per-view level, and quickly ran into an issue with stale results coming for paginated API calls. The API calls a View and caches it, and hence per-view = per-query as far as terminology goes. In retrospect, I can't think how per-query caching can be practically useful, unless the caching is just for extremely short amount of time. Say my API has 2 pages of results, with item IDs 1 - 10 and then 11 - 20. The first page was generated at T, is cached, and will expire at T + 2. The second page was generated at T + 1 and will expire at T + 3. Now due to whatever business logic, say ID 11 moves to page 1 result and ID 10 moves to page 2. At T + 2, a call is made to page 1 and it now caches the results with ID 1 - 9 + 11. Immediately a call is made to page 2, and it will return from cache the results with IDs 11 - 20, which is stale data and incorrect in this scenario. So taking this forward, if the … -
Fundamental django project deployment information
I am a newbie in Django deployment and have been given the task of the project deployment on an Ubuntu 18.04 LTS prod server. I have already deployed the project using NginX and uWSGI by copying all the project files in a directory with appropriate permissions and also assigned respective permissions to www-data user. But, my question is whether all the files need to be directly copied into the said directory (since python files are interpreted files) or is there any other format, such as a war file for jsp projects, that can be directly deployed instead of copying the directory? Thanks. -
Django dateutil attr value error when trying to runserver
When i try to run my server I get this error does anybody know what it means. Let me know if further code/info is needed thanks in advance. File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main from botocore import waiter, xform_name File "C:\Users\dariu\.conda\envs\djangoenv\lib\site-packages\botocore\waiter.py", line 17, in <module> from botocore.utils import get_service_module_name File "C:\Users\dariu\.conda\envs\djangoenv\lib\site-packages\botocore\utils.py", line 27, in <module> import dateutil.parser File "C:\Users\dariu\.conda\envs\djangoenv\lib\site-packages\dateutil\parser.py", line 158 l.append("%s=%s" % (attr, `value`)) ^ SyntaxError: invalid syntax -
Creating medium.com like platform with django-cms or wagtail
I am new to web development and worked my way to find out about the CMS. Requirement: I would like to build a platform like medium.com where subscribers can signup and publish their contents and it should be python based. Question: Therefore, my question is can we use django-cms or wagtail to create such a system? If not, how can i achieve such a system? Any leads to open-source code on github would also be highly helpful. Thankyou! -
Why am I getting this error? UNIQUE constraint failed: app1_comment.user_id
The thing is that I'm creating a comment section for my post, and I want to add an edit button for each comment created by the user, but the thing is that I can only add one comment per user or I get the error in the title, and I'm not sure how to fix this, so here's the code models.py class Category(models.Model): name = models.CharField(max_length= 255) def __str__(self): return self.name def get_absolute_url(self): return reverse('index') class Profile(models.Model): user = models.OneToOneField(User, null = True, on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(null = True, blank = True, upload_to = "images/profile/") website_url = models.CharField(max_length= 255, blank = True, null = True) facebook_url = models.CharField(max_length= 255, blank = True, null = True) twitter_url = models.CharField(max_length= 255, blank = True, null = True) instagram_url = models.CharField(max_length= 255, blank = True, null = True) pinterest_url = models.CharField(max_length= 255, blank = True, null = True) def __str__(self): return str(self.user) def get_absolute_url(self): return reverse('index') class Post(models.Model): title = models.CharField(max_length= 255) header_image = models.ImageField(null = True, blank = True, upload_to = 'images/') author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank = True, null = True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default='coding') snippet = models.CharField(max_length=255) likes = … -
django admin edit form not getting file value
In my html i have a code like : <div class="col-md-4 form-group"> <label for="file1">License<span class="req">*</span></label><br> {% if data.data.licence %} <p class="file-upload">Currently: <a href="/media/{{data.data.licence}}">{{data.data.licence}}</a> <br> Change: <input type="file" name="licence" accept="image/*" id="licence"> </p> {%else%} <input type="file" required name="licence" id="licence"> {%endif%} </div> and in my code i am getting value like : document = request.FILES['licence'] but i am not getting the value in edit form cae whem i am doing this can anyone please help me related this ?? i dont know what i am doing wrong here in my code my add code is working fine where i am getting value from the form and saving data in db like : vendor/licence/ticket.png -
Django Ajax error 403 link forbiden by load() method
I am trying to add a django url(template) in annother one using jquery ajax load() method but there is 403 url forbiden error in the console and when i test the url in the browser the page is displayed views.py def index(request): return render(request,'index.html',{}) def plans(request): plan = Plan.objects.filter(IdPlans=1) return render(request,'plans.html',{'plan':plan}) url.py urlpatterns = [ path('',views.index,name='index'), path('plans/', views.plans, name='plans'),]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) index.html where i want to add <div id="label1">CLICK HERE</div> <section id="liste"> </section> plans.html what i want to add {% for plan in plan %} <article> <img src="{{plan.Image.url}}"> <div> <h2>{{ plan.NamePlan }}</h2> <p>{{ plan.Description }}</p> </div> </article> {% endfor %} JAVASCRIPT LOAD METHOD $(document).ready(function(){ $("#label1").on("click",function(){ $("#liste").load('plans/',{ idcat: idcat, commentNewCount: commentCount }); }); -
Dynamic drop-down menu working on laptop but not mobile when hosted on localhost
I'm trying to make a dynamic dropdown menu and I'm getting it to work on my laptop. But when I host it on my localhost, the drop-down menu doesn't work on any device. I'm following a page to make this dropdown and this is the link. views.py from django.shortcuts import render from . import forms from django.contrib.auth import authenticate,login,logout from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_protect from django.forms import modelformset_factory import requests import urllib.parse from apply_main.models import * def apply(request): def getLonLat(subdistrict,district,state): address = str(subdistrict)+", "+str(district)+", "+str(state) url = 'https://nominatim.openstreetmap.org/search/' + urllib.parse.quote(address) +'?format=json' response = requests.get(url).json() return response[0]["lat"],response[0]["lon"] form = forms.ApplyForm() if request.method == 'POST': form = forms.ApplyForm(request.POST) if form.is_valid(): application = form.save(commit=False) application.save() return HttpResponseRedirect(reverse('apply_main:apply')) context = { 'form':form, } return render(request, 'apply_main/apply_form.html', context) def load_districts(request): state_id = request.GET.get('state') print(state_id,"\n"*5) districts = District.objects.filter(state_id=state_id).order_by('name') return render(request, 'apply_main/dist_dropdown_list_options.html', {'districts': districts}) def load_subdistricts(request): district_id = request.GET.get('district') subdistricts = Subdistrict.objects.filter(district_id=district_id).order_by('name') return render(request, 'apply_main/subdist_dropdown_list_options.html', {'subdistricts': subdistricts}) model.py from django.db import models from django.contrib.auth.models import User class State(models.Model): name = models.CharField(max_length=64) def __str__(self): return self.name class District(models.Model): name = models.CharField(max_length=64) state = models.ForeignKey(State,on_delete=models.CASCADE) def __str__(self): return self.name class Subdistrict(models.Model): name = models.CharField(max_length=64) district = models.ForeignKey(District,on_delete=models.CASCADE) … -
Which is more efficient? Double query or join?
In Django, the foreignkey lookups span relationships as the following: Model student: course ForeignKey (Courses) Model course: instructor ForeignKey(instructors) Model instructor: name CharField So, here's an explanation of an analogue of my question so that someone without knowledge of Django can answer easily. Student.objects.filter(course__instructor = "Mr Paul") is the same as course_list = Course.objects.filter(instructor__name = "Mr Paul") Student.objects.filter(course__in = course_list) And my question is whether a double query is more efficient than a join. The following is the example I am using. However, I would appreciate a more general answer. I assume that in an enterprise application, the number of permissions per model will be ~10 and models will be ~30, so total permissions will be ~100-200. However, the models individually will each have ~10000 records. Based on these numbers, please tell whether a join is more efficient than two subsequent queries. if not isinstance(perm, Permission): try: app_label, codename = perm.split('.', 1) perm = Permission.objects.get(content_type__app_label = app_label, codename = codename) except: raise ValueError() return perm ObjectPermission.objects.filter(user = user, permission = perm) try: app_label, codename = perm.split('.', 1) except: raise ValueError() ObjectPermission.objects.filter(user = user, permission__codename = codename, permission__content_type__app_label = app_label) -
How can I implement a countdown for items in a todo list web app?
I have made a todo list webapp in Django. It is a simple CRUD web App. Now upon creation of an item for the todo list the user specifies a duration for which that item's status remains "to be completed". If the user fails to complete a task in the duration set for an item in the todo list, that item's status should automatically change to "not completed". Should a scheduled job be used to poll the app and change the status accordingly? Wouldn't polling the app constantly be costly? If someone could point me in the right direction I would be grateful. -
How to debug Django while using pipenv and VS Code?
I'm been using VS code and venv for my Django projects and have been able to debug using the tutorial provided by Microsoft here. https://code.visualstudio.com/docs/python/tutorial-django However, I have now switched to pipenv instead which I activate using the commmand pipenv shell. When I now run using the Django debug configuration I get an error. Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I can't find any resources to guide me on this. Do I need to change the launch.json file to make it work with pipenv? -
Sending data to specific webSockets in Javascript for Flask in Django
This question is more theoretical than technical and I have no code to show, I am looking for advice on how to approach the problem. I am working on a project which includes video-calls. An admin schedules the call and invites one or more users to join. The way the 3rd party video-call service I'm using works, the video-call room doesn't exist until the admin joins the call. This means that an admin could schedule a call for 4pm, for example, and invite two people. If the two invitees join before the admin, they are attempting to join an in-existent video-call room, which obviously leads to errors. My solution is to implement a type of waiting room. The idea is the following: the invitee attempts to join the call. If the admin has joined and the room exists, they are connected. If the room does not exist, they are redirected to a waiting room and a websocket is opened. This websocket waits for a notification that the room has been created and upon receiving said notification, executes a function that joins the call. The problem I'm having is that many people could be waiting to join many rooms. What that … -
how do i create an image slider for my website using python
I'm working on a project in which i,m suppose to create an image slide show at the centre of the website. i know how to do this with css and javascript, but i'm willing to use python alone for the project. -
argument of type 'ModelFormMetaclass' is not iterable
please I'm a beginner in django. when i connect my class in the veiws.py i get and error which i don't really understand but when i dont connect it, it works with the class this is my views.py class AudioCreateView(LoginRequiredMixin, CreateView): login_url = 'main:login' model = Audio fields = AudioForm # fields = ['title','audio','author', 'categories'] template_name = 'main/events/create_audio.html' this is my forms.py class AudioForm(ModelForm): class Meta: model = Audio fields = ['id','title','audio','author', 'categories'] # widgets = { # 'audio': forms.FileField(widget=forms.FileInput(attrs={'accept':'application/pdf'})) # please and this is the error i get when i try to use it File "C:\Users\Joe\Desktop\MYDJAN~1\PRIEST~1\env\lib\site-packages\django\forms\models.py", line 551, in modelform_factory return type(form)(class_name, (form,), form_class_attrs) File "C:\Users\Joe\Desktop\MYDJAN~1\PRIEST~1\env\lib\site-packages\django\forms\models.py", line 256, in new apply_limit_choices_to=False, File "C:\Users\Joe\Desktop\MYDJAN~1\PRIEST~1\env\lib\site-packages\django\forms\models.py", line 152, in fields_for_model if fields is not None and f.name not in fields: TypeError: argument of type 'ModelFormMetaclass' is not iterable Can anyone help me i dont understand why im getting this error -
Model got an unexpected keyword argument
I'm getting error as mentioned in title: Policy() got an unexpected keyword argument 'policy_start_date_time', but can't find what is the problem. Here are my codes: models.py: class Policy(models.Model): ... start_date_time = models.DateField(_("Qüvvəyə minmə tarixi"), blank=True, null=True) forms.py: class CreatePolicyForm(ModelForm): def save(self, commit=False): ... class Meta: model = Policy fields = '__all__' widgets = { 'start_date_time': DateTimeInput(attrs={'type': 'date'}), } -
Not passing **kwargs to django-import-export resources from custom view/form
When I use this resources.py inside Django admin everything works fine. However, when I do it on my custom view page there is an issue that popped with the **kwargs user auto-populate. The error must be in my view as it's not passing the **kwargs but I'm not sure how to solve it. Where should I be passing this information? KeyError at /import/ 'user' C:\Users\winkl\tj3\venv\lib\site-packages\import_export\resources.py in import_row self.after_import_instance(instance, new, **kwargs) … C:\Users\winkl\tj3\portfolios\resources.py in after_import_instance instance.created_by = kwargs['user'] resources.py class EntryResource(resources.ModelResource): symbol = fields.Field( attribute="symbol", column_name="symbol", widget=SymbolWidget(Symbol, 'name'), ) date = fields.Field( attribute="date", column_name="date", widget=widgets.DateTimeWidget(format="%Y-%m-%d %H:%M:%S"), ) class Meta: model = Entry fields = ('symbol', 'date', 'id', 'amount', 'price', 'fee', 'entry_type', 'reg_fee',) import_order = fields skip_unchanged = False report_skipped = True def after_import_instance(self, instance, new, row_number=None, **kwargs): print(f' Kwargs: {kwargs}') instance.created_by = kwargs['user'] def after_save_instance(self, instance, using_transactions, dry_run): pass view.py @login_required def import_data(request): if request.method == 'POST': trade_resource = EntryResource() dataset = Dataset() new_trades = request.FILES['importData'] imported_data = dataset.load(new_trades.read().decode('utf-8'),format='csv') result = trade_resource.import_data(dataset, dry_run=True, raise_errors=True) if result.has_errors(): messages.error(request, 'Uh oh! Something went wrong...') else: # Import now trade_resource.import_data(dataset, dry_run=False) messages.success(request, 'Your words were successfully imported') return render(request, 'dashboard/import.html') -
How to use "using" keyword for select database in query for executing in django raw filter?
objs = table.objects.raw(sql).using('cppoi') This is my django filter where i get datas from cppoi database Here sql = "select * from cppoi_sicsmaster" Now i want a sql query which will be fetch datas without django ORM It should use only sql query with selection of the above mentioned database