Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I use query parameters in SQL conditional statement
I am trying to execute a SQL command to return data from the database but using query parameters as a condition in the SQL statement. This is the code I am running and I get this error: def get(self, *args): followers = self.request.query_params.get('') with connection.cursor() as cursor: cursor.execute( "SELECT authapi_user.id AS profile_id FROM authapi_tweet INNER JOIN authapi_user ON authapi_user.id = authapi_tweet.author_id WHERE authapi_tweet.author_id IN %s ORDER BY created_on DESC;", followers) table = cursor.fetchall() return Response(table) return Database.Cursor.execute(self, query) django.db.utils.OperationalError: near "%": syntax error This is an example of the URL request: http://127.0.0.1:8000/api/tweets/alldata/?0=1&1=2 -
Some issues about Django admin
This is my models.py, there is a column called type of holding But when I enter the admin, it is something wrong about that At first i think it is database's problem, but i found that there is nothing wrong with mysql, so can you please help me to find out the problem -
Ci/CD using Google Cloud build with Django on App Engine failed
Background: Trying to automate my build process using the new Google Cloud Build with Django on standard app engine. I started with Django polls example provided by the good Google folks here: https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/appengine/standard_python37/django Environment: Python3.7 with Django 3.0.1 Made a few changes to the above and now my requirements.txt looks like: requirements.txt coverage==5.0.1 Django==3.0.1 entrypoints==0.3 flake8==3.7.9 mccabe==0.6.1 mysqlclient==1.4.6 pycodestyle==2.5.0 pyflakes==2.1.1 pytz==2019.3 sqlparse==0.3.0 app.yaml runtime: python37 handlers: # This configures Google App Engine to serve the files in the app's static # directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to your main app. It is # required when static routes are defined, but can be omitted (along with # the entire handlers section) when there are no static files defined. - url: /.* script: auto env_variables: # the secret key used for the Django app (from PROJECT-DIRECTORY/settings.py) SECRET_KEY: 'DJANGO-SECRET-KEY' DEBUG: 'False' # always False for deployment # everything after /cloudsql/ can be found by entering >> gcloud sql instances describe DATABASE-NAME << in your Terminal # the DATABASE-NAME is the name you gave your project's PostgreSQL database # the second line from the describe output called connectionName can be copied and pasted after … -
Django transaction.atomic() does not work
I have a problem with this code: PhoneNumberFormSet = inlineformset_factory(Person, PhoneNumber, fields=('phone_number',), can_delete=False, extra=1) EmailAddressFormSet = inlineformset_factory(Person, EmailAddress, fields=('email_address',), can_delete=False, extra=1) class PersonCreateView(CreateView): form_class = PersonForm success_url = reverse_lazy('person-list') template_name = 'contacts/person_create.html' def get_context_data(self, **kwargs): data = super(PersonCreateView, self).get_context_data(**kwargs) data['phone_formset'] = PhoneNumberFormSet(self.request.POST or None) data['email_formset'] = EmailAddressFormSet(self.request.POST or None) return data def form_valid(self, form): context = self.get_context_data() phone_formset = context['phone_formset'] email_formset = context['email_formset'] with transaction.atomic(): o = form.save() # <--- this object is saved even when formsets below are not valid condition = phone_formset.is_valid() and email_formset.is_valid() if not condition: return render(self.request, self.template_name, self.get_context_data()) phone_formset.instance = o phone_formset.save() email_formset.instance = o email_formset.save() return super(PersonCreateView, self).form_valid(form) The transaction.atomic() is saving obcject "o" even when phone_formset or email_formset are not valid and view renders forms with errors (object should not be saved) -
Django - Response to `POST` request with file to download
I have a .csv file in my directory And I would like to response to post request (when someone press download button) with that file to download. First I'm handling a request - THERE are more options, like upload a file etc... But when comes post request with val8 I would like to process my csv file with process_file function, return file name and send it to download_file function with request to downloading Here Is my code # HERE I'M GETTING REQUESTS def upload(request): csv_file = "" if "GET" == request.method: return render(request, "main/upload.html") # if not GET, then proceed try: csv_file = request.FILES["csv_file"] except: pass file_type = request.POST.get("type", "") if len(csv_file) > 0: if not csv_file.name.endswith('.csv'): messages.error(request,'File is not CSV type') return HttpResponseRedirect(reverse("upload")) file_data = csv_file.read().decode("utf-8") if file_type == "val2" or file_type == "val3": hikari(file_data, file_type) if file_type == "val4" or file_type == "val5": kokyaku(file_data, file_type) if file_type == "val6" or file_type == "val7": hikanshou(file_data, file_type) return HttpResponseRedirect(reverse("upload")) if file_type == "val8": # HERE I WANT TO RESPONSE WITH FILE TO DOWNLOAD down_file = process_file("hikari") download_file(request, down_file) # HERE IS MY FUNCTION TO RETURN THE FILE def download_file(request, path): if os.path.exists(path): with open(path, 'rb') as fh: response = HttpResponse(fh.read(), … -
Validate a form in backend based on the selected site language
The problem is that for different users the same field may be required or optional to fill out in a form. How to raise an error, same as for as the one shown if the required field was not filled? I would like to raise standard validation because it already has all the translations. P.S. I would like to validate it using backend (without HTML). I will be pleased if you tell me an effective way of raising this error. -
Providing a static default value for a new field in existing objects in model?
I have a model that has 10000 objects and I want to add a new field to it that equals the result of a function acting on another field class MyModel(models.Model): id = models.CharField(max_length=255) field1 = models.CharField(max_length=255) new_field = models.CharField(max_length=255,default=my_func(self.field1)) how can I achieve this? to provide a default value for every object in my DB based upon one of its fields -
create custom decorator for views that check if user is blacklisted
I want to create a decorator for my views that checks the DB if the user has over or equal to 5 warnings, and if so then I redirect him to a page telling him he has been flagged etc. I wrote the code for it but I want to pass the request object to the decorator so I can call request.user for db queries but that doesn't seem like it's possible. How would I go on about this? Decorator: def check_blacklist(request): try: db = blacklist.objects.get(user=request.user) warnings = db.warning if warnings >= 5: return redirect("security:flagged") except: pass models.py class blacklist(models.Model): user = models.ForeignKey(User, default=None, on_delete=models.CASCADE) warning = models.IntegerField() views.py @check_blacklist(request) def task_info(request): return render(request, 'dashboard/task.html',) -
Django. Static files not load
I encountered such a problem, static files (pictures) are not loading in my Django project. The most amazing thing is that I did not change anything, just yesterday, everything worked, and today the pictures are refusing to load. If I follow a direct link to an object, the picture is and opens. However, if you register it in a CSS file, the path to the image is crossed out, and the inscription in the browser debugger "invalid property value" -
how to make to-do tasks for every user in todo list using django
def index(request): todo_list = Todo.objects.order_by('id') form = TodoForm() context = {'todo_list' : todo_list, 'form' : form} return render(request, 'todo/index.html', context) def addTodo(request): form = TodoForm(request.POST) if form.is_valid(): messages.add_message( request, messages.SUCCESS, 'Item Has Been Added', fail_silently=True,) new_todo = Todo(text=request.POST['text']) new_todo.save() return redirect('index') -
Django F object and relativedelta years
Django ORM not working when I do querying like this: F('date_last') - relativedelta(years=1), it returns None for my field. But works with F(date_last) - timezone.timedelta(days=365) So I'm using raw SQL that is working fine, except, that on testing I using sqlite3 database that is not support DATE_ADD function. Any ideas how to support both: mysql and sqlite3 My query: queryset = queryset.annotate( expiration_date=Case( When( accreditation_cycle=Accreditation.ANNUAL_ACCREDITATION_CYCLE, then=RawSQL('DATE_ADD(date_last, INTERVAL %s YEAR)', params=(1, )) ), output_field=fields.DateField() ) ) -
Django - How to create a user-owned group when registering?
I'm using Django. User registration form contains fields such as username, e-mail, password. I want the user to create their own group when registering. How do I add this field? forms.py class RegisterForm(forms.ModelForm): username = forms.CharField(max_length=100, label='Kullanıcı Adı') email = forms.EmailField(max_length=200, help_text='Required') password1 = forms.CharField(max_length=100, label='Parola', widget=forms.PasswordInput) password2 = forms.CharField(max_length=100, label='Parola Doğrulama', widget=forms.PasswordInput) class Meta: model = User fields = [ 'username', 'email', 'password1', 'password2', ] def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError("Parolalar eşleşmiyor!") return password2 def clean_email(self): email = self.cleaned_data.get('email') lenghtw = len(User.objects.filter(email=email)) if lenghtw > 0 : raise forms.ValidationError('Bu email adresine sahip bir kullanıcı zaten var.') return email views.py def register_view(request): form = RegisterForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get('password1') user.set_password(password) #user.is_staff = user.is_superuser = True user.save() new_user = authenticate(username=user.username, password=password) login(request, new_user) return redirect('home') return render(request, 'accounts/form.html', {'form': form, 'title': 'Üye Ol'}) -
Loop in a URL Django
I wanted to access different categories through the URL, is it possible to make a loop or something like that? Which iterates until the end of the URL, no matter how much categories are there. For example my code without this loop is below, and is limited to 6 subcategories. urls.py path('<cat1>/<cat2>/<cat3>/<cat4>/<cat5>/<cat6>', views.AdList.as_view(), name='ad_list'), -
Django 'redirect_field_name' why it returns to index.html page?
after filling the form when I click on save to redirect to 'clinichospital_list.html' but it takes to index.html. it is view.py class class ClinicHospitalCreateView(CreateView): redirect_field_name = 'clinichospital_detail.html' form_class = ClinicHospitalForm model = ClinicHospital it is urls.py path(r'',views.AboutView.as_view(),name = 'about'), **path(r'^list/$',views.ClinicHospitalListView.as_view(),name ='clinichospital_list' ),** path(r'^clinichospital/(?P<pk>\d)/$',views.ClinicHospitalDetailView.as_view(),name = 'clinichospital_detail'), path(r'^clinichospital/new/$',views.ClinicHospitalCreateView.as_view(),name = 'clinichospital_new'), path(r'^clinichospital/(?P<pk>\d)/edit/$',views.ClinicHospitalUpdateView.as_view(), name = 'clinichospital_eidt'), path(r'^clinichospital/(?P<pk>\d)/remove/$',views.ClinicHospitalDeleteView.as_view(),name = 'clinichospital_remove'), and it is forms.py <form class="clinic-form" method="post"> {% csrf_token %} {{form.as_p}} <button type="submit" class="save btn btn-default" name="button">Save</button> -
Authenticated user post DJANGO, save form
I am creating an app where user can search for recipes by ingredients. I want that logged in user can add recipe by himself. I have created form where i am using ModelForm. Now i want to do that after user push submit recipe will be add to recipes which i can see in admin panel and also it will be possible to search for it, but now it looks like it is impossible to save the new recipe... My code in view: def add_recipe(request): if not request.user.is_authenticated: return redirect('login_required') add_recipe = RecipeForm template = "drinks/add_recipe.html" return render(request, template, {'RecipeForm': add_recipe}) def post_recipe(request): form = RecipeForm(request.POST) if form.is_valid(): recipe_name = form.cleaned_data['recipe_name'] preparation = form.cleaned.data['preparation'] ingredients = form.cleaned.data['ingredients'] template = "drinks/search_results.html" return render(request, template, {'form': form, 'recipe_name': recipe_name, 'preparation': preparation, 'ingredients': ingredients}) My form: from django.forms import ModelForm from drinks.models import Recipe class RecipeForm(ModelForm): class Meta: model = Recipe fields = ['recipe_name', 'preparation', 'ingredients'] My templates add_recipe: <h1>Add recipe</h1> <form method="post" action=""> {% csrf_token %} <table> {{RecipeForm}} </table> <input type="submit" value="Submit Form"/> </form> -
Many-to-Many Relationships - Movie - Role - Actor
I'm not sure what is the best solution to describe this conceptual model. I know how to create a many to many relationship, but not with role inside this relation. Could you please let me know what is the best way to do it? Thanks a lot. -
Django is validating formset that has no value selected for required field
I've just started playing with formsets. No idea what I'm doing at the moment. I've got to the point where a form with formset is being saved to the database. However, if nothing is selected for the required field "ledger" then validation still passes, and Django throws up "Key error". My forms.py: class JournalEntryForm(forms.Form): date = forms.DateField(widget=DateTypeInput()) description = forms.CharField(required=False) class LineItemForm(forms.Form): ledger = forms.ModelChoiceField(queryset=Ledger.objects.all()) description = forms.CharField(required=False) project = forms.ModelChoiceField(queryset=Project.objects.all(), required=False) cr = forms.DecimalField(decimal_places=2, required=False) dr = forms.DecimalField(decimal_places=2, required=False) My function in views.py. I've marked line 33 which is the line where the "key error" occurrs. @login_required def entries_new(request): # Takes form and returns form set. So we now have a form set. LineItemFormSet = formset_factory(LineItemForm, extra=2) if request.method == 'POST': journal_entry_form = JournalEntryForm(request.POST) lineitem_formset = LineItemFormSet(request.POST) if journal_entry_form.is_valid() and lineitem_formset.is_valid(): q0 = JournalEntry(user=request.user, date=journal_entry_form.cleaned_data['date'], type="JE") q0.save() for lineitem_form in lineitem_formset: q1 = LineItem( journal_entry=q0, ledger=lineitem_form.cleaned_data['ledger'], #<---- This is line 33 referenced in the error cr=lineitem_form.cleaned_data['cr'], dr=lineitem_form.cleaned_data['dr'], project=lineitem_form.cleaned_data['project'], ) q1.save() messages.success(request, "Journal entry successfully saved.") return HttpResponseRedirect(reverse('journal:entries_show_all') ) else: journal_entry_form = JournalEntryForm() lineitem_formset = LineItemFormSet() context = { 'journal_entry_form': journal_entry_form, 'lineitem_formset': lineitem_formset, } return render(request, 'journal/entries_new.html', {'journal_entry_form': journal_entry_form, 'lineitem_formset': lineitem_formset}) The error I get in my browser: KeyError at … -
Can't login to django admin despite correct superuser credentials
I am configuring openedx ecommerce which uses django admin. I have successfully created a superuser credential as shown below: However when I try to login to the admin panel the page submits and I am presented with the same login page with cleared fields - as shown below: The log files do not update when attempting to login but there are some error messages that I can't seem to work out: Dec 26 15:10:09 ip-172-31-21-194 [service_variant=ecommerce][django.request] WARNING [ip-172-31-21-194 2638] [/edx/app/ecommerce/venvs/ecommerce/local/lib/python2.7/site-packages/django/core/handlers/base.py:152] - Not Found: / Dec 26 15:10:09 ip-172-31-21-194 [service_variant=ecommerce][django.request] WARNING [ip-172-31-21-194 2638] [/edx/app/ecommerce/venvs/ecommerce/local/lib/python2.7/site-packages/django/core/handlers/base.py:152] - Not Found: / Dec 26 15:10:09 ip-172-31-21-194 [service_variant=ecommerce][django.request] WARNING [ip-172-31-21-194 2638] [/edx/app/ecommerce/venvs/ecommerce/local/lib/python2.7/site-packages/django/core/handlers/base.py:152] - Not Found: / Dec 26 17:29:35 ip-172-31-21-194 [service_variant=ecommerce][django.security.csrf] WARNING [ip-172-31-21-194 2635] [/edx/app/ecommerce/venvs/ecommerce/local/lib/python2.7/site-packages/django/middleware/csrf.py:160] - Forbidden (CSRF token missing or incorrect.): /admin/login/ Dec 26 17:29:35 ip-172-31-21-194 [service_variant=ecommerce][django.security.csrf] WARNING [ip-172-31-21-194 2635] [/edx/app/ecommerce/venvs/ecommerce/local/lib/python2.7/site-packages/django/middleware/csrf.py:160] - Forbidden (CSRF token missing or incorrect.): /admin/login/ Dec 26 18:24:26 ip-172-31-21-194 [service_variant=ecommerce][django.request] WARNING [ip-172-31-21-194 2635] [/edx/app/ecommerce/venvs/ecommerce/local/lib/python2.7/site-packages/django/core/handlers/base.py:152] - Not Found: / Dec 26 18:24:26 ip-172-31-21-194 [service_variant=ecommerce][django.request] WARNING [ip-172-31-21-194 2635] [/edx/app/ecommerce/venvs/ecommerce/local/lib/python2.7/site-packages/django/core/handlers/base.py:152] - Not Found: / Dec 26 18:24:26 ip-172-31-21-194 [service_variant=ecommerce][django.request] WARNING [ip-172-31-21-194 2635] [/edx/app/ecommerce/venvs/ecommerce/local/lib/python2.7/site-packages/django/core/handlers/base.py:152] - Not Found: / -
How to handle multi-file input field in Django
I have a database that tracks items. Each item can have multiple images associated with it. My models look like this: class Item(models.Model): name = ... price = ... description = ... class ItemImage(models.Model): item = models.ForeignKey("Item", on_delete=models.CASCADE, related_name="images") Before trying to add the images field, my views looked like this: class ItemAdd(CreateView): model = Item fields = ['name', 'price', 'description'] ... class ItemEdit(UpdateView): model = Item fields = ['name', 'price', 'description'] ... In order to add this new images field, I changed my views to say this: class ItemAdd(CreateView): model = Item form_class = ItemEditForm ... class ItemEdit(UpdateView): model = Item form_class = ItemEditForm ... And created this form: class ItemEditForm(forms.ModelForm): images = forms.ImageField(required=False, widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = Item fields = ('name', 'price', 'description') This adds the file input field to my templates, but doesn't actually do anything with the images the user chooses. Django's documentation has some info on how to handle multiple file uploads here, which is where I got the above images field code, but the sample code doesn't appear to be aware of models at all. If the form being edited is in the CreateView, and the Item doesn't exist yet, I could … -
Display Multiselect bootstrap drop-down value in div with checkbox options
I have a multiselect bootstrap drowdown. I want to display the selected values from a drop-down in a separate div as rows with multiple checkboxes to select. How I can proceed for this? Like I have selected 3 items(I1,I2,I3) from dropdown then i should display all the three items as rows with 5 checkboxes to select in each row. The count of checkbox is fixed. This div should not be available on page load and clearing the values of dropdown. Any idea would help.Thanks. -
Time lapse that repeats every week in django
I have an application that receives the day of the week and the time an event should occur, as well as the number of days before the event for users to confirm attendance. My model follows below: def validar_apenas_um(obj): model = obj.__class__ if model.objects.count() > 0 and obj.id != model.objects.get().id: raise ValidationError("Você só pode adicionar um horário") class ModelPresenca(models.Model): DIAS = ( ('Domingo', 'Domingo'), ('Segunda', 'Segunda'), ('Terça', 'Terça'), ('Quarta', 'Quarta'), ('Quinta', 'Quinta'), ('Sexta', 'Sexta'), ('Sábado', 'Sábado'), ) dia = models.CharField('Dia da Pelada', max_length=10, help_text='Escolha o dia da pelada', choices=DIAS) hora_pelada = models.TimeField('Horário da pelada (ex: 19:30)', help_text='Hora em que sua pelada é realizada') dias_antecedencia = models.PositiveIntegerField('Dias antecedência', default=1, validators=[MinValueValidator(1), MaxValueValidator(6)], help_text='Em quantos dias de antecência os peladeiros devem ' 'marcar presença') I would like this to be repeated every week, opening and closing the confirmation of attendance at the previously set time. I've done a few things apart, which might work, but I can't see a way to keep repeating it. For example, I think of taking the days and converting them to numbers in the "dia_semana" function, then creating, in %Y:%M:%D %H:%M format, the date of the event receiving the day and time. (in the "dia_pelada" function). The "data_inicio_confirmarcao" … -
int() argument must be a string, a bytes-like object or a number, not 'QueryDict'
Recently I am trying to save data into my database when I click on the submit along with default user foreign key. But I am stuck with the error and tried to solve by looking on the web but couldn't find any similar issues. my views.py from django.shortcuts import render,redirect from .models import TimesheetDetails from django.contrib.auth.decorators import login_required # Create your views here. @login_required(login_url="/login") def create_timesheet_view(request): if request.method=="POST": print(request.POST) if ('dateToday' and 'dayToday' and 'startTime' and 'endTime' and 'breakTime' and 'weekType' and 'attendance' and 'normalTime' and 'extraTime' and 'holidayTime' and 'workContent') in request.POST: #post.user = request.POST.get('user') post = TimesheetDetails() post.username = request.POST.get('username') post.date = request.POST.get('dateToday') post.day = request.POST.get('dayToday') post.startTime = request.POST.get('startTime') post.endTime = request.POST.get('endTime') post.breakTime = request.POST.get('breakTime') post.normalTime = request.POST.get('normalTime') post.overTime = request.POST.get('extraTime') post.holidayTime = request.POST.get('holidayTime') post.weekType = request.POST.get('weekType') post.attendance = request.POST.get('attendance') post.content = request.POST.get('workContent') post = TimesheetDetails(request.POST,request.FILES) print (request.POST) instance = post.save() instance.user = request.user instance.save() return redirect('/list') return render(request,'timesheet/create_timesheet.html') def view_timesheet(request): context = {'timesheet_list': TimesheetDetails.obejcts.all()} return render(request,"timesheet/view_timesheet.html") my models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class TimesheetDetails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="timesheet",null="False") date = models.CharField(max_length = 10) day = models.CharField(max_length = 10) startTime = models.CharField(max_length =10) endTime = models.CharField(max_length =10) breakTime = … -
iam using react.js and django for backend i want to upload an image from react.js form to django using axios lib
this is my handle submit function i tried this way but there is something missed i think ''' handle = (event) => { event.preventDefault(); const name = event.target.name.value; const barcode = event.target.barcode.value; const category = event.target.category.value; const description = event.target.description.value; const image=new FormData(); image.append('image',event.target.image.value); axios.post('http://127.0.0.1:8000/admindashboard/products-create/', { name: name, Barcode: barcode, category: category, description: description, image }).then(result=>{console.log(result); }); } ''' and this is my form ''' this.handle( event )} class="ui form"> <Form.Field> <input placeholder='product Name' name='name'/> </Form.Field> <Form.Field> <TextArea placeholder='Description' name='description' /> </Form.Field> <Form.Field> <input placeholder='Barcode' name='barcode'/> </Form.Field> <Form.Field name='category' control='select'> {this.state.categories.map((cat)=>(<option name='category' value={cat.id}>{cat.name} </option>))} </Form.Field> <Form.Field> <input id="id_image" type="file" name="image"/> </Form.Field> <Button type='submit'>Submit</Button> </Form> ''' -
having an Error with STATIC_ROOT when using heroku in Django
"django.core.exceptions.ImproperlyConfigured: You’re using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path." having this error despite me having sett the STATIC_ROOT "STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')" -
Free website to help building & developing web app with python
I wanted to build a web app with python. For a test, Is there any websites that offers free servers, like cloud or Virtual servers which i can build and test my web app using python with it? And is there any websites which i can build my web app for free, like wix.com where we can build our own website... I want something or somewhere that helps me to practice with Python & Django to build a web app.