Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django modelform is not inserting data
I have a Modelform that works great and the redirect happens normally without raising an error. but the data is not inserted into the table, here are my files : models.py class Item(models.Model): # custom validators alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.') # fields dress_name = models.CharField(max_length=20, null=False, verbose_name='وصف الفستان', help_text='مثال: فستان سواريه احمر') dress_size = models.ForeignKey(Size, on_delete='DO_NOTHING', verbose_name='مقاس الفستان') dress_color = models.ForeignKey(Color, on_delete='DO_NOTHING', verbose_name='لون الفستان') dress_image1 = models.ImageField(upload_to='documents/%Y/%m/%d', null=False, verbose_name='الصورة الأساسية للفستان', help_text='لا يمكنك تركها فارغة') dress_image2 = models.ImageField(upload_to='documents/%Y/%m/%d', null=True, verbose_name='صورة إضافية ') dress_image3 = models.ImageField(upload_to='documents/%Y/%m/%d', null=True, verbose_name='صورة إضافة ') dress_action = models.ForeignKey(Action, on_delete='DO_NOTHING', verbose_name='الفستان معروض لل ', help_text='للبيع او للإيجار ') dress_price = models.IntegerField(default=1, verbose_name='السعر') dress_country = models.ForeignKey(Country, on_delete='CASCADE', verbose_name='البلد') dress_city = models.CharField(max_length=80, verbose_name='المدينة او المحافظة') dress_mobile = models.CharField(max_length=20, validators=[alphanumeric], verbose_name='رقم الهاتف ') created_by = models.CharField(max_length=250,) created_at = models.DateField(auto_now=True) dress_active = models.BooleanField(default=False) dress_special = models.BooleanField(default=False) def __str__(self): return self.dress_name forms.py class AddDressForm(ModelForm): class Meta: model = Item exclude = ['created_by', 'created_at','dress_active','dress_special'] views.py def add_dress(request): current_user = request.user all_dress = Item.objects.all() all_dress_s = Item.objects.all().filter(dress_special=True) if request.method == "POST": add_dress_form = AddDressForm(request.POST) if add_dress_form.is_valid(): model_instance = add_dress_form.save(commit=False) model_instance.created_by = current_user model_instance.save() return redirect('home') else: add_cat_form = AddDressForm() context = { 'add_cat_form': add_cat_form, 'current_user': current_user, 'all_dress': all_dress, 'all_dress_s': all_dress_s, … -
How to render different data to the same page by two different views - Django
I'm building a news website.I need display 48 hours most viewed news, this part is in the detail.html page. Now I'm using this method. def newsDetailView(request, news_pk): news = get_object_or_404(News, id=news_pk) News.objects.filter(id=news_pk).update(pv=F('pv') + 1) time_period = datetime.now() - timedelta(hours=48) host_news=news.objects.filter(date_created__gte=time_period).order_by('-pv')[:7] return render(request, "news_detail.html", { 'news': news, 'host_news' : host_news }) It works very well, but my question is ,in oder to use cache conveniently,I want to separate the hot_news functions from def newsDetailView. I have tried : def hot_news(request): time_period = datetime.now() - timedelta(hours=48) hot_news =News.objects.filter(add_time__gt=time_period).order_by('-pv')[:7] return render(request, "news_detail.html", { 'most_viewedh': most_viewedh }) However I can get the data, in deatil.html.I guess the issue is because the url. the link of the deail.html from the index.html is <a href="{% url 'news:news_detail' news.pk %}"> news:news_detail is the url of view def newsDetailView So the url is directly to def newsDetailView and has nothing two do with def hot_news. What should I do, so that I can render the data from def hot_news to the same page as def newsDetailView dose? -
Getting the number of formset's id in Django
In forms.py I have created a formset using formset_factory with extra=6 class Associe(forms.Form): nom= forms.CharField(max_length=40) AssocieFormSet=formset_factory(Associe,extra=6) in my page.html I wrote a loop to write my forms 6 times, but I nead the number in the id, I know Django will give form-0-nom for the first element, and id_form-1-nom for the seconde element and so on, and I know how to get the whole id of the element. But how can I get only the number of each element's id? -
Changing a old Django URL to the new paths
So I am making a new site in Django 2.0 and was following this tutorial on making a user registration form with an activation email and my understanding of the new Django 2 is not good enough so was asking what would be the Django 2 equivalent of this URL url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), -
Filtering a django-tables2 table with django-filters using a drop down list
I have a model (Brief) that i am showing in a list with Django-tables2. A Brief can belong to one or many towers. I am trying to create a view where a user can see all briefs, and then filter to find briefs related to a specific tower. I had first implemented this using check boxes, and it was working, but I need to get that filter into a drop down list. "GET /brief/?towers= HTTP/1.1" - Gives me all the briefs. "GET /brief/?towers=1 HTTP/1.1" - Gives an empty list of briefs.(should give me 2 in my test data) Querying in django shell gives me the results I would expect. Another odd behavior is that my drop down list has spaces that can be selected. class Attribute(models.Model): class Meta: abstract = True ordering = ['name'] name = models.CharField(max_length=100, unique=True) created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='% (class)s_created_by', null=True, blank=True, on_delete=models.SET_NULL) modified_dt = models.DateTimeField(auto_now=True) modified_by = models.ForeignKey(User, related_name='% (class)s_modified_by', null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return self.name class Tower(Attribute): pass class Brief (Attribute): link = models.URLField() sources = models.ManyToManyField(SourceSystem) format = models.ForeignKey(ReportFormat, on_delete=models.PROTECT) towers = models.ManyToManyField(Tower) type = models.ForeignKey(ReportType, on_delete=models.PROTECT) project = models.ForeignKey(Project, on_delete=models.PROTECT) def tower_list(self): return ", ".join([str(obj) for obj in self.towers.all()]) … -
How to configure lighttpd to serve django static files?
I have a web application made with Django 2.0.5, installed in a virtual environment on Debian 9, on which I installed Gunicorn and lighttpd. I installed my web app in /opt/djangoproject/mywebapp. I configured lighttpd adding these lines to my lighttpd.conf $HTTP["url"] !~ "/static" { proxy.server = ( "" => ( ( "host" => "192.168.1.15", "port" => 8001 ) ) ) } alias.url = ( "/static/" => "/opt/djangoproject/mywebapp/mystaticfiles" ) The problem is that the alias only work on port 80 instead of to work on 8001. -
django-haystack: get_absolute_url for searchresult returning list object: ['/test/2018/05/06/something_testing/']
Posting for the first time. please forgive for mistakes. I am trying to build knowledge base site with got haystack working django2.0.3. I can see search results. However, in my search templates for href tag I can see list object for get_absolute_url as "['/test/2018/05/06/something_testing/']". because of this url redirection is not working properly as '[]' these brackets are coming in between. views.py @login_required def techpost_search(request): form = SearchForm() object_list= Techpost.published.all() if request.method == 'GET': form = SearchForm(request.GET) if form.is_valid(): cd = form.cleaned_data query= request.GET.get('query') # results = Techpost.published.filter(Q(title__icontains=query) | Q(body__icontains=query)) results = SearchQuerySet().models(Techpost).filter(content=cd['query']) total_results = results.count() return render(request, 'rincon/search.html', {'form':form, 'results': results, 'total_results': total_results, 'cd': cd}) return render(request, 'rincon/search.html', {'form':form,}) search_index.py class TechpostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) publish = indexes.DateTimeField(model_attr='publish') title = indexes.CharField(model_attr='title') author = indexes.CharField(model_attr='author') url = indexes.CharField() def get_model(self): return Techpost def index_queryset(self, using=None): return self.get_model().published.all() def prepare_url(self, obj): return (''.join(obj.get_absolute_url())) search.htmL {% block content %} {% if "query" in request.GET %} <h4>techposts containing "{{ cd.query }}"</h4> <h5>Found {{ total_results }} result{{ total_results|pluralize}}</h5> {% for result in results %} {% with techpost=result %} <a href="{{ techpost.url}}">{{ techpost.title }} </a> <p class="date"> Published {{ techpost.publish }} by {{ techpost.author }} </p> {% endwith %} {% empty %} <p>There … -
File upload with Django Channels 2
I am creating a chat application using Channels 2, I have been able to implement a one-one chat plus a chat room but just cannot figure out how to handle file uploads. Any idea would go a long way -
Migrate users from database to another on Django
I already have an existing website running and want to transfer just the users (usernames, passwords and emails) to another database for a separate Django website as I am rebuilding it. -
Weasyprint issue in django app with apache
I have a app with Weasyprint to generate pdf, in local enviroment its no problem, but in a virtual machine server with apache, static folder dont work in pdf files (image and style are not show). My question is, is there any package that im ignoring or that is required for Weasyprint to work in apache in a production environment? Besides, I have a production server in google cloud and there it works, with exactly all the same packages. My list of apt-packages: build-essential python3-dev python3-pip python3-cffi libcairo2 libpango1.0-0 libgdk-pixbuf2.0-0 libffi-dev shared-mime-info My list of pip packages: WeasyPrint -
django queryset able update own model's field with existing value + 1?
sorry if the title does not make too much sense, I am not sure how to put it in a correct way with only little words. Anyways, what I really want is...I know we can filter querysets then use update to update all the fields in the queryset without doing a loop then save() But what I really need here is something like...... User.objects.filter().update(username=this is where I want to update BUT I want to update itself's username+1) if I do it in a loopie way, it'll be something like all_users = User.objects.filter() for user in all_users: user.username = user.username + str(1) user.save() but is there a way to use update and do that? Thanks in advance for any help. -
How to call python function from javascript with ajax in django
I want to display the range of the selected car without refreshing the page. This code doesn't give an error but also doesn't do the trick. index.html <select class="custom-select d-block w-100" name="car" id="car" onchange="display(this.value)"> {% for car in cars_list%} <option value="{{ car }}">{{ car }}</option> {% endfor %} </select> main.js function display(value){ $.ajax({ type: "POST", url: "/get_car_data/", data: { car_model: value} }).done(function(range) { alert("test") $("#range").html(range); }); } views.py def get_car_data(car_model): cars_frame = pd.read_csv("C:/Users/David/Desktop/cars.csv", sep=';') frame2 = cars_frame.set_index('Car', drop=True) car_range = (frame2.loc[car_model]['Range']) return car_range urls.py urlpatterns = [ url(r'^get_car_data/', views.get_car_data, name='get_car_data'),] -
How to upload a file only to django database but not to my fileSystem?
I can upload files, into Django database and into my filesystem at the same time, but I don´t need the file to store in my fileSystem, How can I upload a file throw a form and throw the view.py only to my database. here is my code to upload the file to my database and into my filesystem: from django.core.files.base import ContentFile f = open(file_path, 'r') object.image.save('image.jpg', ContentFile(f.read())) -
How can I fill a fiend with current user in form using CreateView/UpdateView in Django
I've been looking for this for few days and I couldn't solve it, so here is my problem: I'm trying to create a product using just CreateView in views.py for now (My idea is to create forms and pass everything to a function in views.py), but there is one field that I want it to be auto-filled with the logged user ('owner'). I've tried using the get_initial in the createView for now, but it doesn't work. I want to say that this it actually creates a form in which I have to fill all the fields and it works fine, but I want to auto-fill the 'owner' field with the current user logged in. For now I tried to use the get_initial as I said before, but seems that it does not work. I also tried lots of things that I've seen here, in stackoverflow, but any of them worked for me. Here I put all the relevant code, but if you need anything else please, ask for it and I'll upload it. This is my views.py: # view for the product entry page class ProductCreate(CreateView): model = Product fields = ['owner', 'category', 'tag', 'name', 'content_tweet'] success_url = reverse_lazy('index') def … -
How to get data from last 48 hours - Django
I'm building a news website.I need display 48 hours most viewed news. So I need first to get the 48 hours news, and then get its pv. Currently I'm using a very complicated method which is from a tutorial: def get_two_days_read_data(content_type): today = timezone.now().date() dates = [] read_nums = [] for i in range(2, 0, -1): date = today - datetime.timedelta(days=i) dates.append(date.strftime('%m/%d')) read_details = ReadDetail.objects.filter(content_type=content_type, date=date) result = read_details.aggregate(read_num_sum=Sum('read_num')) read_nums.append(result['read_num_sum'] or 0) return dates, read_nums My question is, is there any easier way? For example something like this: def newsDetailView(request, news_pk): news = get_object_or_404(News, id=news_pk) tags = news.tag.annotate(news_count=Count('news')) all_comments = NewsComments.objects.filter(news=news) News.objects.filter(id=news_pk).update(pv=F('pv') + 1) 48_hours_hot_news = news.objects.filter(**48_housrs**).order_by('-pv') return render(request, "news_detail.html", { 'news': news, 'tags': tags, '48_hours_hot_news' : 48_hours_hot_news 'all_comments': all_comments, }) Any friends can help?Thank you so much! -
Material design bootstrap extended panel like in Google Form
I am developing app in Django and using bootstrap with Material Design CSS and JS I am looking for easy way to imitate behaviour of the google forms page So I am looking for a way, that you have a table row (or a div) and on click this row or div extend, add new elements and buttons on it and raise it with left color decoration. I kind off make this, but the procedure is not so simple and it is not made as "template" to use it on different pages, projects,... Because it seams to me, that this behaviour is standard in Google products, I am asking if there is some standard/easy procedure for achieving this. -
djangorestframework date out of range error
I am trying to store a max date but djangorestframework is unable to serialize the field.How can i refactor the END_TIME field to make it serializable from django.utils import timezone END_TIME = timezone.make_aware(timezone.datetime.max - timezone.timedelta(days=1), timezone.get_default_timezone()) date_end = models.DateTimeField(dafault = END_TIME) Error is "Datetime value out of range" USE_TZ = True pytz is installed -
Django queryset If statement never evaluates to true?
I have a simple update view. That reads the POST request from a previous view. This part works great. owner = ADMirror.objects.get (employeentname=request.POST.get('userpost')) I have a query set defined as: currentlevel = QVReportAccess.objects.filter(ntname = 'owner.employeentname, active = 1).values('sr_datareduce_summary_code') which the print looks like: <QuerySet [{'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_c ode': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_sum mary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_dataredu ce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_da tareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, { 'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z0712 6'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, '...(remaining elements truncated)...']> The query set will have duplicates for the sr_datareduce_summary_code because they are at individual program levels in the model. I then have the following if statement to give a yes if true and no if false, but even though the queryset contains Z07126 my if statement never evaluates to true. Why is this and how can I get it to work correctly? if QVReportAccess.objects.filter(ntname = owner.employeentname, active = 1).values_list('sr_datareduce_summary_code') == "Z07126": appaccess = 'yes' else: appaccess = 'no' print(appaccess) -
Django messaging framework
I'm trying to get the messaging framework of Django 2.0 working. Upon successfully sending a form, the success message should be displayed on the index.html page. However, no messages are displayed. What am I doing wrong? The installation appears to be correct, since moving the required code to a template that is rendered by the PostDetailView (that the absolute url links to) does display the messages. Furthermore, the SuccessMessageMixin only includes a success message. Is a similar mixin available for errors, warnings, etc.? views.py from django.views.generic import CreateView, DeleteView, DetailView, ListView, UpdateView from django.contrib.messages.views import SuccessMessageMixin from .forms import PostModelForm from .models import Post class PostCreateView(SuccessMessageMixin, CreateView): model = Post form_class = PostModelForm success_message = 'You have successfully created a new Post.' index.html <!-- DOCTYPE html --> <html> <head> <title></title> </head> <body> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} {% block content %} {% endblock %} </body> </html> -
Django Join Query - Show Only Categories With One Post or More
Hi I'm trying to get some help on a join query. I have a Deals model and a Retailer model. The Retailer model is a foreign key of my Deals model. Looks like this class Deal(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=140, unique=True) description = RichTextUploadingField(default='') retailer = models.ForeignKey(Retailer, on_delete=models.CASCADE) image = VersatileImageField('deal image', upload_to=deal_upload_path, null=True, blank=True) img_alt = models.CharField(max_length=140, default='') link = models.URLField(max_length=2000, default='') category = models.ForeignKey(Category, on_delete=models.CASCADE) date_added = models.DateField(default=timezone.now) date_expires = models.DateField(default=timezone.now) price = models.CharField(max_length=140) secondary_price = models.CharField(max_length=140, default='') likes_total = models.IntegerField(default=1) expired = models.BooleanField(default=False) handpicked = models.BooleanField(default=False) class Retailer(models.Model): company = models.CharField(max_length=140) slug = models.SlugField() I'm just trying to get a list of my retailers that have at least one deal. I have a context_processor that looks like this but I'm having a hard time determining the best way to change this to what i need. Any ideas? def retailers(request): return { 'stores': Retailer.objects.all().order_by('company') } -
Update Function View in Django is not saving the editings
When im writing or editing something in front_end of my,its not saving those editing. it redirect to detail view and shows earlier data.where am i doing wrong? my code Models.py from django.db import models from django.template.defaultfilters import slugify # Create your moels here. class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(blank=True,default='') body = models.TextField() created_date = models.DateTimeField(auto_now_add=True,blank=True,null=True) def __str__(self): return self.title def save(self, *args,**kwargs): if not self.slug: self.slug = slugify(self.title) super(Post,self).save(*args,**kwargs) Forms.py from .models import Post from django import forms class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title','body'] app/urls.py urlpatterns = [ path('post/<int:pk>/edit/',views.edit_view, name = "edit_view")] Views.py def edit_view(request,pk): try: post = Post.objects.get(pk=pk) except: raise Http404('Page Not Found') form = PostForm(request.POST or None,instance= post) print(request.method) if request.method == 'POST': if form.is_valid: form.save() return redirect('detail_view', pk=pk) else: return render(request, 'edit.html',{'form_edit': form}) Template edit.html <form method="post" > {% csrf_token %} {{form_edit.as_p}} <input type="submit" value="ok"> </form> -
Django test error: Column does not exist
Postgresql, Django 2.0, Python 3.6.4 After running a migration that changed the name of a field desktop_pay to simply pay, I'm getting an error when running manage.py test saying the column pay does not exist. Here's the migration: from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('instructions', '0055_auto_20180517_1508'), ] operations = [ migrations.RenameField( model_name='instruction', old_name='desktop_pay', new_name='pay', ), ] Here's the error: > python .\manage.py test Creating test database for alias 'default'... Traceback (most recent call last): File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: column instructions_instruction.pay does not exist LINE 1: "...on"."quota", "instructions_instruction"."target", "instructi... ^ If I start a psql prompt, though, I can clearly see that the column does exist, at least in the "real" table. mydatabase=> \d+ instructions_instruction Table "public.instructions_instruction" Column | Type | Collation | Nullable | Default | Storage | Stats target | Description ---------------------+------------------------+-----------+----------+------------------------------------------------------+----------+--------------+------------- id | integer | | not null | nextval('instructions_instruction_id_seq'::regclass) | plain | | quota | smallint | | not null | | plain | | pay | numeric(5,2) | | not null | | main | | ### etc... What's going on here? Why is Django not finding the column? How can I debug this? -
django admin: exclude not working in change_form
I have the following admin class: from django.contrib import admin class CommandAdmin (admin.ModelAdmin): list_display = ('name','status','get_requester', 'justification') readonly_fields = ('name','status','get_requester', 'request', 'justification') exclude = ('request',) def get_requester(self,obj): return obj.request.requester get_requester.command_order_field = 'requester' #Allows column order sorting get_requester.short_description = 'Who Requested' #Renames column head def get_form(self, request, obj=None, **kwargs): self.exclude = ['request'] form = super(CommandAdmin, self).get_form(request, obj, **kwargs) return form def get_queryset(self, request): print request qs = super(CommandAdmin, self).get_queryset(request).select_related('request') return qs.filter(status='pending', request__isnull=False) The Command model looks like this ... class Command(models.Model): name = models.CharField(max_length=128) nonroot_risk = models.IntegerField(default=1) nopasswd_risk = models.IntegerField(default=0) base_risk = models.IntegerField(default=1) status = models.CharField(max_length=150, default='pending') comment = models.TextField(blank=True, null=True, help_text='Comment by the approver, typically about why the risk ' 'rating was determined to be as such.') high_risk_justification = models.TextField(blank=True, null=True) justification = models.CharField(max_length=2000, blank=True, null=True) request = models.ForeignKey('sudorequests.Request', blank=True, null=True) When I get to the change form the 'Request' object still appears on the form. Here's a screen shot: -
Can't run test on the Python/Django application
Well I have already grant the user to 'CREATEDB'. but when I run the test using python manage.py test I got this error, Creating test database for alias 'default'... Got an error creating the test database: permission denied to create database -
Form valitation Django Form __init__ redefined
Hello every one thanks to try to help me to solve this issue my code views.py def update(request): id = request.POST.get('id') form = AddForm(request.POST,company= Choic().list_company_form()) if form.is_valid(): message = services.update_(form.cleaned_data['name']...(more args with the same method),id) return render_to_response('result.html',{'message':message}) forms.py class AddForm(forms.Form): def __init__(self, company=(), *args, **kwargs): super(AddForm, self).__init__(*args, **kwargs) self.fields['company'].choices = company name = forms.CharField(label='Name', max_length=50) ... company = forms.ChoiceField(choices=(), required=True, label='Company:') before i redefined the init method in the form class all work, i changed cause the choices in company field needs, also there's something missing in the configuration or else, i need to validate the form and use this method (cleaned_data['name'])to send to mi services class thanks to trying to help me.