Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access denied error only on heroku remote machine through requests python
I am facing this issue where when I access the page source of a url from my local machine it works fine but when I run the same piece on code on a heroku machine it shows access denied. I have tried changing the headers ( like adding Referers or changing the User-Agent) but none of those solutions are working. LOCAL MACHINE ~/Development/repos/eater-list master python manage.py shell 1 ↵ 12051 21:15:32 >>> from accounts.zomato import * >>> z = ZomatoAPI() >>> response = z.page_source(url='https://www.zomato.com/ncr/the-immigrant-cafe-khan-market-new-delhi') >>> response[0:50] '<!DOCTYPE html>\n<html lang="en" prefix="og: http' >>> response[0:100] '<!DOCTYPE html>\n<html lang="en" prefix="og: http://ogp.me/ns#" >\n<head>\n <meta charset="utf-8" REMOTE MACHINE ~ $ python manage.py shell Python 3.5.7 (default, Jul 17 2019, 15:27:27) [GCC 7.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from accounts.zomato import * >>> z = ZomatoAPI() >>> response = z.page_source(url='https://www.zomato.com/ncr/the-immigrant-cafe-khan-market-new-delhi') >>> response '<HTML><HEAD>\n<TITLE>Access Denied</TITLE>\n</HEAD><BODY>\n<H1>Access Denied</H1>\n \nYou don\'t have permission to access "http&#58;&#47;&#47;www&#46;zomato&#46;com&#47;ncr&#47;the&#45;immigrant&#45;cafe&#45;khan&#45;market&#45;new&#45;delhi" on this server.<P>\nReference&#32;&#35;18&#46;56273017&#46;1572225939&#46;46ec5af\n</BODY>\n</HTML>\n' >>> ZOMATO API CODE There is no change in headers or requests version. class ZomatoAPI: def __init__(self): self.user_key = api_key self.headers = { 'Accept': 'application/json', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) ' … -
NoReverseMatch at URL
I've been trying to create a movie survey in Django for an assignment, and I am currently working on the function. I can't seem to understand why won't it recognize the URL I pass. I tried removing the hardcoded URL as shown in the Django tutorial on the framework's site, but that doesn't make the error go away. Here's an excerpt from urls.py: urlpatterns = [ url(r'^$', views.index, name="index"), path('movie=<int:movie_id>&user=<int:user_id>/', views.movie, name='movie'), path('ratings/', views.ratings, name='movie'), path('rating/<int:movie_id>/', views.rating, name='movie'), path('movie=<int:movie_id>&user=<int:user_id>/vote/', views.vote, name='vote'), path('register/',views.register, name='register'), ] This is my movie view( supposed to present a movie and a star rating radio for the user to rate the movie), where the URL is constructed and passed to HTML: def movie(request,movie_id,user_id): movie = get_object_or_404(Movie, pk=movie_id) voteURL = '/polls/movie=' + str(movie_id) + '&user='+str(user_id)+'/vote/' context = { 'mymoviecaption':movie.Title, 'moviePoster': 'https://image.tmdb.org/t/p/original'+tmdb.Movies(movie.TMDBID).images().get('posters')[0].get('file_path'), 'myrange': range(10,0,-1), 'myuserid':user_id, 'voteurl': voteURL, 'mymovieid':movie_id } #print(nextURL) translation.activate('en') return HttpResponse(render(request, 'movieview.html', context=context)) The HTML excerpt, where the vote view is called: <form action="{% url voteurl %}" method="post"> {% for i in myrange %} <input id="star-{{i}}" type="radio" name="rating" value={{i}}> <label for="star-{{i}}" title="{{i}} stars"> <i class="active fa fa-star" aria-hidden="true"></i> </label> {% endfor %} <input type="submit">Vote!</input> </form> The vote view( should save to database and redirect to the … -
Django form from JavaScript
I'm trying to create a server using Django where the user creates figures such as markers, lines, polygons, circles, etc in a map, because of that I'm using Leaflet.js. After the user creates what he wants I want the geometry figures (Latitude and Longitude of every figure) and Leaflet have an option for that, however you must download but I don't want so I changed a part of the source code into this. document.getElementById('export').onclick = async function(e) { var data = drawnItems.toGeoJSON(); // make the request: var rsp = await fetch("path/to/server/upload/url", { method: "POST", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }); console.log("server responded with: ", await rsp.json()); } I'm not good at web developing so I lack of knowledge using Django and JavaScript. So my question is the following (probably a noob question): Is there a way to create a form for the geometry figures in order to manipulate it in Python? The entire code is the following: <!DOCTYPE html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <script> L_NO_TOUCH = false; L_DISABLE_3D = false; </script> <script src="https://cdn.jsdelivr.net/npm/leaflet@1.5.1/dist/leaflet.js"></script> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.5.1/dist/leaflet.css"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css"/> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css"/> <link rel="stylesheet" … -
How to get access to model data through two intermediate models?
There are four models: class ObjectDataAdditional(models.Model): #various fields and: normal = models.ForeignKey( 'ObjectDataNormalized', on_delete=models.CASCADE, null=True, related_name='additional_normal' ) class ObjectDataNormalized(models.Model): #various fields class LinkedData(models.Model): many = models.ManyToManyField( ObjectDataNormalized, related_name='many_related', ) def __str__(self): return u', '.join([str(a.pk) for a in self.many.all()]) class LinkedInfo(models.Model): linked_data = models.ForeignKey( LinkedData, on_delete=models.CASCADE, related_name='linked_data_related' ) normalized = models.ForeignKey( ObjectDataNormalized, on_delete=models.CASCADE, related_name='normalized_related' ) main = models.BooleanField( default=False, null=False, ) Here I get data i need: info = LinkedInfo.objects.all().order_by('linked_data_id', '-main').select_related( 'linked_data', 'normalized', ).prefetch_related( 'normalized__normal_object', 'normalized__additional_normal' ).annotate(max_percentage=Max( 'normalized__normal_object__additional_object__percentage_technical_readiness')) final_data = [] temp_data = [] if info: last_link_pk = info[0].linked_data.pk for i, x in enumerate(info): if x.linked_data.pk == last_link_pk: temp_data.extend(create_temp_array(x, x.normalized.additional_normal)) last_link_pk = x.linked_data.pk else: final_data.append(temp_data) temp_data = [] temp_data.extend(create_temp_array(x)) last_link_pk = x.linked_data.pk if info.count() - 1 == i: final_data.append(temp_data) return Response(final_data) Create hierarchy of objects on value of main field in model LinkedInfo: def create_temp_array(data, additional_result=None): additional = data.normalized.additional_normal.filter(normal=data.normalized.pk).values() result = [{ 'linked_data_id': data.linked_data.pk, 'is_main': data.main, 'normalized_object_id': data.normalized.pk, 'name_data': data.normalized.name_data, 'year_data': data.normalized.year_data.year, 'build_code': data.normalized.build_code, 'ministry_code': data.normalized.ministry_code, 'territory_code': data.normalized.territory_code, 'fcp': data.normalized.program_code, 'max_percentage_technical_readiness': data.max_percentage, 'additional': additional }] return result data.normalized.additional_normal.filter(normal=data.normalized.pk).values() executes each call of method create_temp_array() (as it should) but I just can't find another way to put data from additional_object to created array. Each object ObjectDataNormalized may have a few objects ObjectDataAdditional … -
How to change django admin permissions based on a field value?
I have a model where a Professor belongs to a certain department Class Professor(models.Model): name=models.CharField(max_length=50) code=models.CharField(max_length=9) dept=models.ForeignKey('Department', on_delete=models.CASCADE) Where the model for the department is just its name with multiple professors pointing to it. Would there be a way to set view or edit permissions depending on the value of the department name? Say, if I want professors that belong to department A to only be editable by people with permissions to A, and professors belonging to department B to be editable by people with permissions to B and so on, what would be the way to implement it in the admin? -
How to provide read-only access for unauthorized users to my React/Django app?
I have a social media-type web app and want to have some read-only access even when a user isn't logged in. For example, if the user votes on a poll, I want nothing to happen but the user should still be able to see it. I am using token authorization. I'm wondering, should I do a check on the front-end somehow to see if a user is logged in (perhaps checking for the existence of a token in local storage) and not perform a fetch if they're not? Or should I somehow, in the frontend, handle receiving a 401 response from the backend for trying to access a protected resource? Or should I handle it on the back end and send back a 200 response and let the front end handle receiving a different version of a 200 response? I'm using Django and React -
How can I change the template used for django-ckeditor to browse?
Djago-Ckeditor use a default html template rendered when url /ckeditor/browse/. I want to know if I can change the html templete for one of my own that handle the same features but with a pretty design. This is the default template: image of the window displayed Also if it is possible to add a delete button as well. -
How do I set up a ThemeForest theme in a Django project?
I recently got started with Django, took a few courses on it and got the basic idea in terms of project structure, urls, templates, static files etc. To avoid learning frontend development (and build my app faster), I thought a bootstrap theme would be a good option. I got this https://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469 which has bootstrap4 in the title, however, it seems that integrating it into the project is not as simple as placing the scss, js and vendor files into my static folder. The 'getting started' resources suggest that it runs on NodeJS, and has a whole backend of its own. I'm not asking for a bespoke full guide on how to do it, but it'd be nice to know if the two things are compatible or I if should move on and try some other frontend solution instead. Cheers! -
Transfer date and time from Django model to Javascript and save the object again
I have a serializer class and a view which convert Django model and it can be shown in a template. # models.py class Book(models.Model): title = models.CharField(max_length=65, null=True, blank=False) published_at = models.DateTimeField(blank=True) # serializer.py class BookSerializer(serializers.ModelSerializer): published_at = serializers.SerializerMethodField() def get_published_at(self, obj): published_at = obj.published_at return published_at class Meta: model = Book fields = ('title', 'published_at') Using the serializer class, one can send the data to a template. Here, the value of published_at is in the ISO date format. Such as: 2019-10-17T21:57:56Z I need to show it in an HTML/Javascript form as local time and then again send the date object to Django to update the published_at field. How can this be achieved? -
Is there a way to reload ViewSet on each GET request for new data in DRF?
I am trying to generate a random object from my Model. The problem is that it will only work one time, then I have to restart the server to get a new object. It just keeps giving me the same object until the restart. I have been looking for solution on stack overflow but haven't found any. Views.py def dailyaskist(category): qs = Task.objects.filter(category=category) max_num = len(qs) while True: pk = random.randint(1, max_num) task = Task.objects.filter(pk=pk).first() if task: return task.pk class DailyTaskEcommerceViewSet(viewsets.ModelViewSet): category = 'ecommerce' task_pk = dailyaskist(category) queryset = Task.objects.filter(pk=task_pk) serializer_class = TaskSerializer serialisers.py class StepSerializer(serializers.HyperlinkedModelSerializer): task_id = serializers.PrimaryKeyRelatedField(queryset=Task.objects.all(), source='task.id') class Meta: model = Step fields = ('title', 'description', 'done', 'task_id') class TaskSerializer(serializers.HyperlinkedModelSerializer): steps = StepSerializer(many=True, read_only=True) class Meta: model = Task fields = ('title', 'description', 'video', 'done', 'steps') models.py Categories = ( ('ecommerce', 'Ecommerce'), ) class Task(models.Model): title = models.CharField(max_length=50) description = models.TextField(max_length=360) video = models.CharField(max_length=30, default='') category = models.CharField(choices=Categories, default='', max_length=30) done = models.BooleanField(default=False) def __str__(self): return self.title class Step(models.Model): task = models.ForeignKey(Task, related_name='steps', on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField(max_length=360) done = models.BooleanField(default=False) def __str__(self): return self.title I want to receive a new object (task) each time I make a GET request using the DailyTaskEcommerceViewSet. Thanks in … -
django queryset gives me an syntaxerror as result
I'm trying to import a model in views.py so i can add a modelobject to context which will render to the html template , but instead it returns an syntaxerror. This is what views.py looks like: from django.shortcuts import render from .models import Food def detail_view(request): print request food = Food.objects.all().first() template = "detail_view.html" context = { "title": "Hello , Detail" "food": food } return render(request, template, context) This is what models.py looks like: from django.db import models # Create your models here. class Food(models.Model): title = models.CharField(max_length=20) description = models.TextField(null=True, default="Description will be placed here") price = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) def __unicode__(self): return self.title Note: im using django 1.8.6 and python 2.7 -
KeyError: 'password1': password1 = self.cleaned_data['password1']
I am trying to implement registration in Django and faced with error: forms.py line 17, in clean_password KeyError: 'password1': password1 = self.cleaned_data['password1'] How can I solve the error? Full code of the application located here (branch Login-version-2-site ): https://github.com/mascai/reg_app/tree/Login-version-2-site models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.dispatch import Signal from .utilities import send_activation_notification class AdvUser(AbstractUser): is_activated = models.BooleanField(default=True, db_index=True, verbose_name='Пpoшeл активацию?') send_messages = models.BooleanField(default=True, verbose_name='Слать оповещения о новых комментариях?') class Meta(AbstractUser.Meta): pass user_registrated = Signal(providing_args=['instance']) def user_registrated_dispatcher(sender, **kwargs): send_activation_notification(kwargs['instance']) user_registrated.connect(user_registrated_dispatcher) forms.py class RegisterUserForm(forms.ModelForm): email = forms.EmailField(required=True, label="Email address") password1 = forms.CharField(label="Password", widget=PasswordInput, help_text=password_validation.password_validators_help_text_html()) password2 = forms.CharField(label="Password", widget=PasswordInput, help_text=password_validation.password_validators_help_text_html()) def clean_password(self): password1 = self.cleaned_data['password1'] if password1: password_validation.validate_password(password1) return password1 def clean(self): super().clean() password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: errors = {'password2': ValidationError('Введённые пароли не совпадают', code='password_mismatch')} raise ValidationError(errors) else: return self.cleaned_data def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data['password1']) user.is_active = False user.is_activated = False if commit: user.save() user_registrated.send(RegisterUserForm, isinstance=user) return user class Meta: model = AdvUser fields = ('username', 'email', 'password', 'password2', 'first_name', 'last_name', 'send_messages') urls.py from .views import BBLoginView, BBLogoutView, profile, RegisterUserView, RegisterDoneView, user_activate urlpatterns = [ path('', views.post_list, name='post_list'), path('accounts/login/', BBLoginView.as_view(), name='login'), path('accounts/profile/', profile, name='profile'), path('accounts/logout/', BBLogoutView.as_view(), name='logout'), … -
How to setup path (urls) for multiple Django applications in a single Django project
I have a single Django project which has two different Django applications, MyApp1 and MyApp2 (changed their names). The structure is like this: MyProject MyApp1 static templates urls.py views.py ... MyProject settings.py urls.py ... I wrote the MyApp2 as a separate application in a different Django project and integrated it with the MyProject project (pip install MyApp2). Here is the installed apps in the settings.py file: # Application definition INSTALLED_APPS = [ 'MyApp1', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MyApp2', ] These are the following paths (urls.py) of the MyProject. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('myapp1/', include('myapp1.urls')), path('', include('myapp1.urls')), path('myapp2/',include('myapp2.urls')), ] These are the following paths (urls.py) of the MyApp1: from django.urls import path from . import views from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('about/', views.about, name='about'), path('contact/', views.contact, name='contact'), ] These are the following paths (urls.py) of the MyApp2: from django.urls import path from . import views urlpatterns = [ path('', views.login, name='login'), path('index', views.home, name='home'), path('dashboard_output', views.dashboard_output, name='dashboard_output'), path('login', views.login, name='login'), ] On the browser, if I type http://127.0.0.1:8000/ or http://127.0.0.1:8000/myapp1 I get the view of the MyApp1. On the browser, … -
How to set sessionid in cockie in Angular 7, to save session_key for multiple async requests?
I'm setting a Django server which exposes an endpoint, that receives many post calls (20/second) from the same client (an angular application running on http://localhost:4200/). I need to save the session_key for this client(), since there are some session variables that gets updated with each request. The problem is that the session is not getting saved on client's side. Each request comes with session_key = None From postman it saves the session perfectly, and all works as expected. I noticed that postman sets a cookie from the client in the first call: Cookie: sessionid=en2ghiz6df8xoy4v45fhqatx0c820bqb; path=/; domain=localhost; HttpOnly; Expires=Sat, 09 Nov 2019 23:41:56 GMT; The following snippet show how the django server set the id: def detect(request): # initialize the data dictionary to be returned by the request if request.method == "POST": print(request.session.session_key) if not request.session.exists(request.session.session_key): request.session.save() print(request.session.session_key) The desired result output(this is using postman) [26/Oct/2019 22:33:37] "GET /get_result/ HTTP/1.1" 500 70124 #comes with an initial session_key id and don't needs to create new one #maintains the session_key for next requests en2ghiz6df8xoy4v45fhqatx0c820bqb [27/Oct/2019 16:23:18] "POST /face_detection/detect/?= HTTP/1.1" 200 0 en2ghiz6df8xoy4v45fhqatx0c820bqb [27/Oct/2019 16:23:21] "POST /face_detection/detect/?= HTTP/1.1" 200 0 en2ghiz6df8xoy4v45fhqatx0c820bqb [27/Oct/2019 16:23:24] "POST /face_detection/detect/?= HTTP/1.1" 200 0 Actual result ouput using Angular client: … -
Can I make the automatic collection field before click submit in Django?
Can I make the automatic collection field before click submit in form Django? I illustrate the idea with the attached drawingenter image description here -
Django Writing database migrations forward function issue
I'm trying to add custom migration to django app. I want that the custom migration wouldn't work with "default" database and another custom migration works with only "default" database. I apply method suggested in django documentation but migration commands never worked. How can i fix this issue? Thanks for helps. Django documentation page: [https://docs.djangoproject.com/en/2.2/howto/writing-migrations/][1] My code (0001_initial.py,only works with "default" database): from django.db import migrations, models def forwards(apps, schema_editor): if schema_editor.connection.alias == 'default': migrations.CreateModel( name='Planets', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('description', models.TextField(blank=True)), ], ), class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.RunPython(forwards), ] Other migration (only works with non "default" databases): from django.db import migrations, models def forwards(apps, schema_editor): if schema_editor.connection.alias != 'default': migrations.CreateModel( name='data_sources', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('sql_query', models.TextField(default='')), ], ), migrations.CreateModel( name='query_history', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('query', models.TextField()), ('date', models.DateField(auto_now_add=True)), ], ), class Migration(migrations.Migration): dependencies = [ ('universe','0001_initial') ] operations = [ migrations.RunPython(forwards), ] -
How to create correct notifications with django getstream?
I create notifications system with getstream.io in Django and works good but, in one situation I don't know how to correctly do this. I have Django and this app: https://github.com/GetStream/stream-django Normally I create notification as in tutorial in link above, and this work well. class Follow(models.Model, Activity): @property def activity_notify(self): return [feed_manager.get_notification_feed(self.target_user.id)] Now I need something difficult. I have 3 models. class Goal(models.Model, Activity): title = models.CharField(max_length=255, verbose_name='Tytuł') image = models.ImageField(blank=True, verbose_name='Tło') body = HTMLField(verbose_name='Treść') votes = GenericRelation(LikeDislike, related_query_name='goalvotes') created_at = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) class Joined(models.Model, Activity): goal = models.ForeignKey(Goal, on_delete=models.CASCADE, related_name='joined_goal') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='joined_users') created_at = models.DateTimeField(auto_now_add=True) and class Comment(models.Model, Activity): body = models.TextField() created_at = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=CASCADE) and my goal is to send notification about new comment in goal to all users who already joined to goal. I try something like this: @property def activity_notify(self): return [feed_manager.get_notification_feed(Joined.user.id)] I know this is wrong, but I have no other idea how to do this. Maybe someone have solution. -
django error in http://127.0.0.1:8000/ Page not found (404)
Sorry for my basic question but I'm learning and I can't identify the error *Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in proyectoapettito.urls, Django tried these URL patterns, in this order: admin/ AppApettito/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.* whit /index *Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/index Using the URLconf defined in proyectoapettito.urls, Django tried these URL patterns, in this order: admin/ AppApettito/ The current path, index, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.* url app from django.urls import path from . import views urlpatterns=[ path('',views.index, name='index'), ] url project from django.contrib import admin from django.urls import path from django.urls import include urlpatterns=[ path('admin/',admin.site.urls), path('AppApettito/',include('AppApettito.urls')), ] views app from django.shortcuts import render from .models import Menu # Create your views here. def index(request): return render(request, 'AppApettito/index.html', {}) -
zip and formset together in django template
im trying to use formset_factory and something from my db in zip and use it in to template here is my form: class class_attandance_form(forms.ModelForm): choise1 = [(True, 'ح'), (False, 'غ')] choise2 = [('مثبت', 'مثبت'), ('منفی', 'منفی')] attendance = forms.ChoiceField(required=True, choices=choise1) activity = forms.ChoiceField(required=False, choices=choise2) score = forms.CharField(required=False, max_length=3) user = forms.CharField(required=False,max_length=20) class Meta: model = Class_Book fields = ('activity','attendance','score','user') and here is my view: def class_attendance(request): term = Term.objects.filter(lesson__in=[1,]) form1 = formset_factory(class_attandance_form,max_num=len(term),extra=len(term)) form = form1() term_form = zip(list(term), list(form)) if request.method == 'POST': query = form1(request.POST or None) if query.is_valid(): q = query.cleaned_data print(q) return render(request,'teacher/class_attendance.html',{'term_form':term_form}) and my temp is : <form role="form" method="post"> {% csrf_token %} <table cellspacing="0" class="table"> <thead> <tr> <th>ردیف</th> <th>نام و نام خانوادگی</th> <th>حضور و غیاب</th> <th colspan="2">نمره</th> </tr> </thead> <tbody> {% for term, form in term_form %} <tr class="class_book" id="{{ term.id }}"> <td>{{ forloop.counter }}</td> <td>{{ term.student.first_name }} {{ term.student.last_name }}</td> <td> {{ form.attendance }} </td> <td> {{ form.activity }} </td> <td> {{ form.score }} </td> </tr> {{ form.user }} <script> $('#id_form-{{ forloop.counter0 }}-user').val({{ term.id }}) </script> {% endfor %} </tbody> </table> <button id="submit" class="button" type="submit">ثبت</button> </form> why when i use query = form1(request.POST or None) i got this error "ManagementForm Data is Missing When … -
How Can I Declare File in travis config file?
I created simple django project and i stored secret key, variable etc. in keys.json file. It gives this error when i try to build project: FileNotFoundError: [Errno 2] No such file or directory: 'keys.json' How can i fix it. My .travis.yml file: python: - "3.7" install: - pip install -r requirements.txt script: - python manage.py test - python manage.py runserver 0.0.0.0:8000 -
How to use FilePond in Django project
Background: I have two models: SellingItem and SellingItemImages. SellingItemImages has a custom FileField that can take multiple files. By putting two forms(itemform and imageform) under single element (enctype="multipart/form-data"), I was able to allow users to upload multiple images. Now, I want to incorporate client side image optimization and better UI. I tried out filepond but am facing some challenges. I organized this post by showing django code without filepond showing code with filepond what I accomplished with filepond so far questions on what to do next ** 1)django code without filepond.** models.py # models.py class SellingItem(models.Model): seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=200) description = models.CharField(max_length= 500, null=True, blank=True) price = models.IntegerField(default=0) class SellingItemImages(models.Model): sellingitem = models.ForeignKey(SellingItem, default = None, on_delete=models.CASCADE, related_name='images') image = ContentTypeRestrictedFileField(content_types=['image/png', 'image/jpeg','image/jpg'],blank=True, max_upload_size=5242880) #ContentTypeRestrictedFileField is a custom FileField. Here is forms.py class SellingItemForm(forms.ModelForm): class Meta: model = SellingItem fields = ('name', 'description', 'price') class SellingItemImagesForm(forms.ModelForm): class Meta: model = SellingItemImages fields= ('image',) widgets = { 'image': forms.FileInput(attrs={'multiple':True,}), } Here is views.py @login_required def post_newitem(request): if request.method == 'POST': itemform = SellingItemForm(request.POST) imageform = SellingItemImagesForm(request.POST, request.FILES) if '_cancel' in request.POST: itemform = SellingItemForm() imageform = SellingItemImagesForm() return render(request, 'market/post_newitem.html', {'itemform': itemform, 'imageform': imageform}) else: if '_publish' in … -
Django: Assign a group to new user per type
I'm using table inheritance in my authentication system, so the User model has 4 types inheriting from it. normaladmin, manager, operator, worker, each one has its own table since they have different attributes, and there is a group for each table. so when anyone registers, he selects his group, and when the instance is created i need to assign it to its group. i have seen this, it suits the problem but not exactly my case, because i need to specify to which group i want to assign the instance to. so i need help on how i can do this, specify the group name to which i want to assign the instance. -
Need workaround for limit in Django mysql query
This line does not work: specific_info = Special.objects.filter(specialid=pk).order_by('description')[:1] This is the error that I get after switching from SQLite to MYSQL: (1235, "This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'") Is there a workaround to do limits in Django with a MYSQL Database? -
Unable to load celery application
I am having the following error: Error: Unable to load celery application. The module teste was not found. when calling the command line: celery -A teste worker -l info -P gevent in other forum questions, it is recommended to change the name of celery.py, check the directories, and they ask if there is a init.py None of those answers suited my issue. I'd appreciate if you could help me and explain to me what I might be doing wrong (not keen on neither Python nor Django just yet). Here's the celery.py inside my teste app (folder) # from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'teste.settings') app = Celery('teste') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() # @app.task(bind=True) # def debug_task(self): # print('Request: {0!r}'.format(self.request)) Here's the init.py # from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) -
Avoid n+1 queries in Django admin list view
I have a Django model: class Book(models.Model): title = models.CharField(max_length=30) @property def slug(self): return slugify(self.title) Now if I add slug field to admin list_display, there will be a separated query for each instance. How to make just one query for all instances? I tried to use select_related in the ModelAdmin class, but I did not get it working.