Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin page 404
When I try to navigate to the admin section of my django app, I get a not found error: project/urls.py from django.conf.urls import include, url from django.contrib import admin from app.views import View1, View2 from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', View1.as_view(), name="view_1"), url(r'^another_view/(?P<pk>\d+)$', View2.as_view(), name="view_2"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app/urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), (r'^/', include('app.urls')), ] settings.py .... BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'app/static'),) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' MEDIAFILES_DIRS = ( os.path.join(BASE_DIR, 'app/media'),) .... When I try to navigate to localhost:8000/admin, I get the following error: Page Not Found (404) Using the URLconf defined in app.urls, Django tried these URL patterns, in this order: ^$ [name='view_1'] ^another_view$ [name='view_2'] ^media\/(?P<path>.*)$ The current URL, admin, didn't match any of these. -
Django Booleanfiedl Checkbox and Label displays in two lines
I have a registration form with Django 1.8. I am asking the user to select checkbox "I have read and agree to the Terms of Use". The issue is on the form the label and boolenfield checkbox are on two lines. For example "Terms&Conditions" 1st line, Checkbox and helptip - 2nd Line. Is there any way to have all in one line like: Terms&Condition [BooleanField]checkbox forms.py ..... iAgree = forms.BooleanField(label=_("Terms&Conditions")) addm.html ... <p> {{userform.iAgree.label_tag}} {{userform.iAgree}} <a title="Please accept that you have read the Terms of Use" href="#" class="helpIcon tooltip"><span title="help"></span></a> </label> </p> -
Python, Django - ValueError: "<...>" needs to have a value for field "..." before this many-to-many relationship can be used
Dear StackOverflow community. My question is related to the insertion of a new record to the table that contains a many2many fields field. I spent the entire day trying to resolve this problem by myself, read the django documentation and surfing in stackoverflow. My models.py : from django.db import models from django_extensions.db.models import TimeStampedModel class clans(TimeStampedModel): rfam_acc = models.CharField(max_length=7) rfam_id = models.CharField(max_length=40) description = models.CharField(max_length=100) author = models.CharField(max_length=100) comment = models.CharField(max_length=2000, null=True) class Meta: ordering = ('rfam_id',) def __str__(self): return self.rfam_id class families(TimeStampedModel): rfam_acc = models.CharField(max_length=7) rfam_id = models.CharField(max_length=40) description = models.CharField(max_length=75) author = models.CharField(max_length=100) clan = models.ManyToManyField(clans, null=True, blank=True) comment = models.CharField(max_length=2000, null=True) my script for the data collection (from another database) and insertion in my DB: ( this is run from manage.py shell_plus ). import mysql.connector from browse.models import clans, families def run(): #... Query from another DB # Query for clans using cursor. assign results to list of lists row_clans query_clans = ("SELECT c.clan_acc, c.id, c.description, c.author, c.comment FROM clan c") cursor_clans.execute(query_clans) row_clans = cursor_clans.fetchall() # Creation of entry clans in the database. for clan in row_clans: clap = clans.objects.create( rfam_acc=clan[0], rfam_id=clan[1], description=clan[2], author=clan[3], comment=clan[4], ) # Query for families, that have clan = just created clan. … -
How to verify google captcha in django view
Hi I am trying to implement google Captcha to Django Form but I am not able to get the view to verify the captcha class FinancingForm(forms.ModelForm): captcha = NoReCaptchaField() class Meta: model = Financing fields = '__all__' def __str__(self): return self.first_name def submit_financing(request): template = loader.get_template('project/submit.html') print ("display new seller") if request.method == 'POST': print ("got post") print (request.POST) form = FinancingForm(request.POST) if form.is_valid(): print ("valid") financing = form.save() send_mail( 'New Financing application', 'New Financing application.', 'from@example.com', ['info@gmail.com'], fail_silently=False, ) else: print ("invalid data") print (form.non_field_errors) print (form.errors) pass context = { } return HttpResponse(template.render(context, request)) -
Decouple and Dockerize Django and Celery
I wondering what the best way is to decouple Celery from Django in order to dockerize the two parts and use docker swarm service? Typically one starts their celery workers and celery beat using a command that references there Django application: celery worker -A my_app celery beat -A my_app From this I believe celery picks up config info from settings file and a celery.py file which is easy to move to a microservice. What I don't totally understand is how the tasks would leverage the Django ORM? Or is that not really the microservices mantra and Celery should be designed to make GET/POST calls to Django REST Framework API for the data it needs to complete the task? -
Django Modelform setting minimum Value on FloatField
i am trying to set the min_value Attribute on Form level within my modelform. Forms.py class ProductForm(forms.models.ModelForm): class Meta: model = Artikel localized_fields = '__all__' fields = ('price',) Model.py class Artikel(models.Model): price = models.FloatField(help_text ='Price') How can i setup the modelform that i can constrain the values allowed on the modelform? I want the user to only enter values greater than or equal to 0.01. I dont want to restricted on Database Level cause i dont want to limit myself in that regard. -
Django ModelChoiceField with empty_label as valid input
I'm using the following form to generate a dropdown list with my registered users: class TaskAssignUserForm(forms.Form): user = forms.ModelChoiceField(queryset=User.objects.all().order_by('username')) Inside my template I render the above form together with a submit button. The application user can choose from the registered users to select one and assign him/her to a task. This is working, if a user and not the empty label (--------) was selected. But, I want the empty label as a valid option too, to cancel the assignment between the task and the user. I'm working with the following views.py and looking for an option to check if the empty label or an empty choice was made. if form_TaskAssignUserForm.is_valid(): task.user_assigned = form_TaskAssignUserForm.cleaned_data['user'] task.save() else: if # check if emtpy label is set task.user_assigned = None task.save() I found out that checking if form_TaskAssignUserForm.cleaned_data['user'] exists could be an option but I feel not comfortable with that. There should be a way that works together with the .is_valdid() check. Is there a djangonian way solving that problem? Bye, aronadaal -
how to get id in the url after submission of form
I am using django forms to add a new object(page) to the db and after submitting the form i want to redirect to the url of page detail but the problem is that i didn't have the id of the page that is being created. I'm new to django so please help me in this. model.py file class UserPage(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) cover_page = models.FileField() page_name = models.CharField(max_length=250) forms.py from django import forms from .models import UserPage class PageForm(forms.ModelForm): class Meta: model = UserPage exclude = ['user'] fields = [ "page_name", "cover_page" ] view.py def create(request): if request.user.is_authenticated(): if request.method=='POST': form = PageForm(request.POST , request.FILES) if form.is_valid(): instance = form.save(commit = False) instance.user = User.objects.get(id=request.user.id) instance.save() else: form = PageForm() context = { "form" : form, } return render(request, 'pages/create.html', context) else: messages.error(request, "please Login First") return HttpResponseRedirect(reverse('index')) url.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^(?P<page_id>[0-9]+)/$', views.pageDetail, name='pagedetail'), url(r'^create/$', views.create, name='create_check'), ] -
How to execute an order_by after using distinct?
I would like to sort my result after I have grabbed unique results based on two fields. The problem I'm having is that I cannot use two order_by in Django. Django clears the previous order_by() whenever you use this function. Each order_by() call will clear any previous ordering. Example of models: class Product(models.Model): price = models.FloatField() name = models.CharField(max_length=100) group = models.CharField(max_length=100) I want to get the product which is in the same group and have the lowest price. Then, I'd like to sort them by price. Something like this: Product.objects.order_by('group','price').distinct('group').order_by('price') -
jQuery code inside search results django haystack
I have django app 1.8 (django-haystack==2.4.1) and in this place of my app I have problem with search results. I get a little part of text, then I get jQuery code: <p>{% highlight other.raw_content with search_query html_tag "b" max_length 300 %}</p> I have no idea how to hide this part of code or fix this problem. -
How create an API with access to a subordinated console application?
I want to create an API. My problem is I do not know what is the right technique and which topics I have to learn to achieve my goal. I saw a django tutorial where they create an API. There was a Get-Request and they Respond with a JSON document filled from the database. I want to fill the JSON document with data from an c++ console application which is doing some calculation. I have no clue how I can link the external c++ console application with django. Is django the right framework for my problem or do I have to use other techniques? Please point me in the right direction. I am totally lost :) -
Custom middleware doesn't redirect
I'm writing a simple custom middleware that is supposed to redirect all users to a specific page if a settings constante is set to True: from django.shortcuts import redirect from django.conf import settings class DisableSiteMiddleware( object ): """If site is disabled, user is redirected to a simple page""" print( "Class" ) def process_request( self, request ): print( "func" ) if settings.SITE_DISABLED == True: return redirect( "/site-disabled" ) In urls.py, but does it with any url url( r'^site-disabled/', site_disabled ) What happens is curious: on browser side it won't load anything and display a browser failure page. On the console I can see it prints repeatedly "func" which means that process_request is called several times. I suspect a loop being killed by the browser. What could be the issue ? -
Django: Can someone please explain what save_base with the argument raw=True does?
New to Django and programming and can't seem to find any official documentation for save_base with the argument raw=True. Can someone please spell it out to me what it does? Haven't been able to find any google results that give a thorough explanation. Any help is appreciated. -
Django website optimization: Too many calls to core python functions?
I am trying to optimize load time of page and found one request which is fetching data and taking ~6-7sec. I used runprofileserver of django-extensions and found out that it is not database which is causing delay but excessive call to core python methods. Have a look on top 30 time intensive calls Here we can see that mostly due to large number of call to in-build python methods this request is taking more than 5sec to execute. I want to know, are following conclusions right? SQL queries or ORM is not major culprit (Though it is data intensive request but it ranks on 6th with 0.194 sec) ? There is not much scope of optimization as major calling are happening to in-build python functions of posixpath.py and genericpath.py ? Can you please suggest ways, if any, to optimize this after looking above data? -
How to send some arguments along with CreateView and then access them in the template?
I was making a online store kind of website and am not able to make my add to cart option to work properly. I haven't yet linked the rest of the code to the button and am using an another link to operate it currently as you can see in the code.I want the form to submit the item name and brand automatically. Please suggest some way. urls.py url(r'^(?P<pk>[0-9]+)/addtocart/$', views.ItemAdd.as_view(), name='addtocart'), models.py class Mycart(models.Model): name = models.CharField(max_length=250) brand = models.CharField(max_length=250) quantity = models.IntegerField(default='1') def __str__(self): return self.name def get_absolute_url(self): return reverse('products:detail', kwargs={'pk': self.pk}) views.py class ItemAdd(CreateView): model = Mycart fields = ['name', 'brand', 'quantity'] template_name = 'products/add_to_cart.html' def get_context_data(self, **kwargs): context = super(ItemAdd, self).get_context_data(**kwargs) return context add_to_cart.html {% extends 'products/base.html' %} {% block body %} <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="hidden" name="name" value="{{ object.name }}"> <input type="hidden" name="brand" value="{{ object.brand }}"> <br> <p>Enter Quantity</p> <input type="number" name="quantity" value=""> <button type="submit" class="btn btn-success">Submit</button> </form> {% endblock %} -
Strip doesn't work correctly when stripping path
I'm facing a weird problem. In Django, I need to strip path so I get relative path from absolute but strip doesn't work correctly. I've created a property of model which should strip the path and return subpath but it strips only a part from left side and part from right side. >>> Language.objects.get(name="Albanian").flag u'/home/django/SolutionsForLanguages/static/img/flags/550px/am.png' >>> settings.BASE_DIR '/home/django/SolutionsForLanguages' >>> Language.objects.get(name="Albanian").flag.strip(settings.BASE_DIR) u'c/img/flags/550px/am.p' >>> Language.objects.get(name="Albanian").flag.lstrip(settings.BASE_DIR) u'c/img/flags/550px/am.png' Do you know what causes this problem? -
How to add permissions to users during registration in Django?
I have a registration method in views.py def register_page(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = User.objects.create_user(username=form.cleaned_data['username'], password=form.cleaned_data['password1'], email=form.cleaned_data['email']) if request.POST.get("admin", ""): import pdb;pdb.set_trace() content_type = ContentType.objects.get_for_model(User) permission = Permission.objects.get(codename='admin_can_manage_users') user.user_permissions.add(permission) new_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1']) login(request, new_user) return redirect('payment_list') form = RegistrationForm() variables = RequestContext(request, {'form': form}) return render_to_response('registration/register.html',variables) I also have a register form with standart fields and additional manually-added checkboxes. I want to check if one checkbox is checked and if so add permissions to users. <form method="post" action="."> {{ form.as_p }} <input type="radio" class='radio-button' name="regular" id="regular"/><label for="regular">User</label> <input type="radio" class='radio-button' name="manager" id="manager"/><label for="manager">Manager</label> <input type="radio" class='radio-button' name="admin" id="admin"/><label for="admin">admin</label> <input type="submit" value="register" /> </form> Now permissions aren't assigned automatically. -
Making password visible in Django forms CharField (where widget=forms.PasswordInput)
In a Django form, I'm getting users to input their usernames and passwords like so: from django.contrib.auth.forms import AuthenticationForm class ReauthForm(AuthenticationForm): username = forms.CharField(max_length=254) password = forms.CharField(label=_("Password"), widget=forms.PasswordInput) class Meta: exclude = ("username",) fields = ("password",) Is there any parameter I can pass into the widget method (or something else) that allows the password to be visible as it's typed? -
InMemoryUploadedFile - TypeError - not working in session handling
I am uploading an image and requesting it in a view. It print the file but it returns an error with InMemoryUploadedFile:sample_img.jpg (image/jpeg)> is not JSON serializable print request.FILES print request.FILES['cover_photo'] request.session['content_pic'] = request.FILES['cover_photo'] How can i access an image field in session. I need to save the image file after getting all the info and at last after maintaining in the session need to save the file. My page contains the journey of three levels 1) upload an image - 1st page 2) getting the details of the image concept - 2nd page 3) displaying the details of the information(In this page i need to display the image by accessing in session ) - 3rd page 4) save the image and other details Please let know how can i handle it -
invalid literal for int() with base 10: 'N21706' - Django
After searching I've found out that the problem is related to the ForeignKey. It is expecting to return the id but I want to use the tail number. I've tried many ways but I don't seem to understand how it works. I'm doing a ForeignKey into the model of a different app. The two apps are called dispatch (app2) and add_acft (app1). The views that I'm having the errors on are on the dispatch app. Thanks in advance for anything you can do to help me understand. add_cft models.py from django.db import models import datetime class AddAcft(models.Model): YEAR_CHOICES = [] for r in range(1940,(datetime.datetime.now().year+1)): YEAR_CHOICES.append((r,r)) make = models.CharField(max_length=10,blank=False,null=False) make_model = models.CharField(max_length=10,blank=False,null=False) tail = models.CharField(max_length=7,blank=False,null=False) year = models.IntegerField(('year'),choices=YEAR_CHOICES, default=datetime.datetime.now().year) serial_number = models.IntegerField(blank=False,null=False) updated = models.DateTimeField(auto_now_add=False,auto_now=True) def __str__(self): return self.tail dispatch models.py from django.db import models import datetime from django.core.urlresolvers import reverse from add_acft import models as aircraft_models shced_type_choices = (('rental','rental'), ('instruction','instruction')) class Reservation(models.Model): res_number = models.AutoField(primary_key=True) date = models.DateField(default=datetime.date.today()) status = models.CharField(max_length=10,default="Created") reservation_type = models.CharField(max_length=11,choices=shced_type_choices, default="rental") tail = models.ForeignKey(aircraft_models.AddAcft) renter = models.CharField(max_length=30,blank=False,null=False) created = models.DateTimeField(auto_now_add=True,auto_now=False) updated = models.DateTimeField(auto_now_add=False,auto_now=True) def __str__(self): return self.renter def get_absolute_url(self): return reverse("reservations:detail", kwargs={"res_number": self.res_number}) dispatch views.py from django.contrib import messages from django import forms from django.http import … -
Django: Redirect already logged user by class based view
I want to redirect to the main page if the user is already authenticated. So I want a redirect from / to /main views.py: class LoginView(FormView): form_class = LoginForm success_url = reverse_lazy('main') template_name = 'module/login.html' def form_valid(self, form): if self.request.user.is_authenticated(): return redirect(settings.LOGIN_REDIRECT_URL) else: username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None and user.is_active: login(self.request, user) return super(LoginView, self).form_valid(form) else: return self.form_invalid(form) settings.py: LOGIN_REDIRECT_URL = reverse_lazy('main') LOGIN_URL = reverse_lazy('login') LOGOUT_URL = reverse_lazy('logout') I tried also to add a get function, but then it call itself only infinite times. def get(self, request, *args, **kwargs): if request.user.is_authenticated(): return HttpResponseRedirect('main') else: return HttpResponseRedirect('/login/') urls.py: url(r'^$', views.LoginView.as_view(), name='login'), url(r'^login/', views.LoginView.as_view(), name='login'), -
Codalab without Azure? (possibly alternatives)
Is it possible to run CodaLab platform without Microsoft Azure? Documentation doesn't mention this possibility and studying code reveals that Azure seems to be tightly-coupled with whole platform (for example: compute/worker.py uses BlobService to store "blobs" and replacing the functionality doesn't seem trivial). Is there something I am missing? Are there any similar platforms? -
How should I build my api?
how should I build my api? website requirements: -register -login -manage database -send request to api -show response from api server requirements: -receive api request from website -do some transformation/validation with the received data(need access to datebase) -communicate with a linux c++ console application(redirect input/output) which does some calculation -wait until the calculation is finished (arround 100ms) -do some transformation/validation with the received data from the c++ console application -send response back to website I thought of the following: website: -django framework with support of html,css,javascript -JSON communication with api -mongoDB server: -linux server (because of the c++ console application) -JSON communication with website I think the website part is fine but how should I built the server part? Should I write a python or c++ program which manage the api request/response and communicate with the c++ console application? Which opportunities do I have? Please point me in the right direction :). Ask, if you need more information. -
Django - using the same foreign key twice in a model
I'm trying to use the same foreign key for two fields in the same model and am getting an error. Im trying to have a primary and secondary on call user, but am not sure how to format the relationship after receiving the errors below class ManualRotas(models.Model): rota_name = models.CharField(max_length=200,choices=settings.ONCALL_ROTAS) primary_user = models.ForeignKey(User, unique=True, verbose_name="Primary OnCall Engineer") p_start_time = models.DateTimeField(verbose_name="Start Time") p_end_time = models.DateTimeField(verbose_name="End Time") secondary_user = models.ForeignKey(User, verbose_name="Backup OnCall Engineer", unique=True,blank=True,null=True) s_start_time = models.DateTimeField(blank=True,null=True, verbose_name="Start Time") s_end_time = models.DateTimeField(blank=True,null=True,verbose_name="Start Time") ERRORS: oncall.ManualRotas.primary_user: (fields.E304) Reverse accessor for 'ManualRotas.primary_user' clashes with reverse accessor for 'ManualRotas.secondary_user'. HINT: Add or change a related_name argument to the definition for 'ManualRotas.primary_user' or 'ManualRotas.secondary_user'. oncall.ManualRotas.secondary_user: (fields.E304) Reverse accessor for 'ManualRotas.secondary_user' clashes with reverse accessor for 'ManualRotas.primary_user'. HINT: Add or change a related_name argument to the definition for 'ManualRotas.secondary_user' or 'ManualRotas.primary_user'. WARNINGS: oncall.ManualRotas.primary_user: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField. HINT: ForeignKey(unique=True) is usually better served by a OneToOneField. oncall.ManualRotas.secondary_user: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField. HINT: ForeignKey(unique=True) is usually better served by a OneToOneField. System check identified 4 issues (0 silenced). -
Clean invalid image form/correct redirect
I develop a pet-ptoject, kinda simple image sharing service and encountered such difficulty. What I have and what trying to get. A homepage which is rendered by 'index' view with model form and 3 queries of images. A user is supposed to select his image from his disk to upload, enter image title (optionally) and press Upload button. In case of invalid image submission (non-image format of due to restrictions) my app should render homepage again with error message, empty form to prevent rise browser's caution about double action. Here's that view from views.py def index(request): # Main page view form = ImageForm(request.POST or None, request.FILES or None) images_recent = Image.objects.order_by('-upl_date')[:IMAGE_COUNT] images_popular = Image.objects.order_by('-rev_count')[:IMAGE_COUNT] images_like = Image.objects.order_by('-like_count')[:IMAGE_COUNT] if form.is_valid(): image = form.save(commit=False) image.user = request.user image.img = request.FILES['img'] image.desc = request.POST.get('desc') image.slug = slug_gen() image.save() messages.add_message(request, messages.SUCCESS, _('Yee haw! Your amazing image uploaded')) return redirect('pyxchange:index') context = { 'form': form, 'images_recent': images_recent, 'images_popular': images_popular, 'images_like': images_like } return render(request, 'pyxchange/index.html', context) What have I fix/add here to solve the problem? Thanks.