Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - page loads incorrectly
In my all web page there is menu that enables us to navigate it to respective url. Lets say in my home page there is a menu called Owner Maintenance that contains few items called create, delete, view and update. When I am in home page and I click on create owner page(sub menu of Owner Maintenance) then it goes to create url, and now in create page also I have menu - Owner Maintenance. If from create owner page if I click view owner sub menu item it should go to its url and vice versa. Code :- 3 html file currently I have - adminHome.html, createOwner.html and viewOwner.html common code snippet for dropdown in html :- <div class="dropdown"> <button onclick="myFunction()" class="dropbtn">Owner Maintainance</button> <div id="actionDropdown" class="dropdown-content"> <a href="ownerMaint">Create Owner</a> <a href="deleteOwner">Delete Owner Details</a> <a href="updateOwner">Update Owner Details</a> <a href="readOwner">View Owner Details</a> </div> </div> urls.py :- urlpatterns = [path('successMsg/', views.success), path('adminMain/',views.adminMain), path('readOwner/',views.readOwner), path('ownerMaint/',views.ownerMaintainance), ] views.py :- def readOwner(request): ownerName = "rrr" if request.method == "POST": MyLoginForm = OwnerDetails(request.POST) if MyLoginForm.is_valid(): ownerName = MyLoginForm.cleaned_data['ownerName'] q = Owner.objects.get(name=ownerName) else: MyLoginForm = OwnerDetails() return render(request, 'main/readOwner.html',{'ownerName': ownerName}) def ownerMaintainance(request): your_name = "not logged in" if request.method == "POST": MyLoginForm = OwnerDetails(request.POST) if MyLoginForm.is_valid(): … -
Django pycharm can't find setting.py and manage.py in my project
enter image description here Help plllz !! -
Django Tests Pass with SQLite, Fail with Other DB's
My Django tests all pass when I use the built-in SQLite as my database. However, when I switch to the built-in MySQL and PostgreSQL, they fail. (All local database servers.) The connections to the DB are live enough -- the database is created and migrations applied. But the tests aren't even hitting views.py before the test server returns a 500 (and no additional explanation beyond "Server Error", even in debug mode). I'm using Django with Django REST Framework, and testing with REST Framework's RequestsClient class. My test fixtures are generated with Factory Boy. Any ideas? I have a vague feeling it's to do with Factory Boy but nothing concrete. The fact that it fails with multiple databases, and successfully builds the tables, makes me suspect it's not the database itself. Versions tested: Django 1.11.6 and 1.11.9 Django REST Framework 3.7.1 Postgres 10.1 MySQL 5.7.21 Factory Boy 2.9.2 -
Django: change language from timesince
I want to change the language of timesince. Do I need to change directly in my django source or is there a way to modify TIMESINCE_CHUNKS variable in the settings file? -
Connecting to an oracle database through Django
I would like to connect to an existing oracle database though Django and write a select statement to query the results. I am a beginner to Django and would like to know the steps to follow to achieve the same. I did change the settings.py file to reflect the changes DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'name', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'host.com', 'PORT': '1521', } } -
Django request.post no data available
I have already searched for similar questions on StackOverflow but could not find the solution that would work for me. I have the following code snippet: def post_request(request): if request.method == "POST": access_token = AccessToken.objects.get(token = request.POST.get("access_token"), expires__gt = timezone.now()) As I get the following response to my request: AccessToken matching query does not exist. , I started debugging the app and found that request.POST = . I have no data in there I am making a POST request in POSTMAN, where I added the data to raw -> form-data. I also tried sending data through raw->json but anyway the request.POST does not contain anything. What is the cause that I have no Post data? How can I get the POST data? Thank you! -
What is the right method to use many to one and one to many relationships in Mongo DB?
I am using mongoengine with Python and Django. models.py for DB Design with mongoengine class Skills(EmbeddedDocument): skill_name = fields.StringField(required=True) class ProfessionalProfile(Document): user_id = fields.IntField(required=True) skills = fields.ListField(fields.EmbeddedDocumentField(Skills)) Note: I am using Django along with Mongoengine so I store the id to document. If we go by this method, each user should have one document right? In SQL we will be using the same table with an extra column with a foreign key to link to the user. The above-mentioned method with mongoengine works! "_id" : ObjectId("5a70b44d8db17c2af0ec3d75"), "user_id" : 2, "skills" : [ { "skill_name" : "Django" }, { "skill_name" : "Photoshop" } ] But is this the right way to do it? -
JSON serialisers and alternative http responses with Django
I'm trying to create a filter system on a click event - using an AJAX post method to update the context that is shown on the template. I'm currently using: return HttpResponse(json.dumps(context), content_type="application/json") To return a response with a context object. However, this doesn't quite work with certain object types: TypeError: is not JSON serializable I know there's something regarding serialisers but I'm currently unable to either a.) use them correctly or b.) use them at all. For some context I'm passing filter variables to the view with the AJAX post method - then: posts = Post.published.filter(category__name__in=category_filter_items) And adding this to my context: context['posts'] = posts Would anyone know the correct way to update the context is such a manner? -
Django+Paramiko SSH
def testssh(request): build = 'DISPLAY=:0 chromium-browser' connection = paramiko.SSHClient() connection.set_missing_host_key_policy(paramiko.AutoAddPolicy()) connection.connect(ip, username='pio', password='piopio') ftp = connection.open_sftp() f = ftp.open('run.sh', 'w+') f.write(build) command = "sh run.sh" stdin, stdout, stderr = connection.exec_command(command) connection.close() return render(request, 'testssh.html') The function writes run.sh to another remote machine and opens the chrome on that machine. The chrome opens many tabs until I stop running the script. It looks like an infinite loop. What did I miss? -
Django 1.11.5 Class based (generic) redirect function with args
Within my created application within Django 1.11.5 I have created update, create and delete functionality using ClassBased or Generic views which do work, however I am having a problem redirecting my user to correct dynamic page. In a instatcne if a user has opened a details page for a specific product, when the user updates the product infromation I want the application to redirect user back to the updated page. As of yet I have achieved this using args by specifing a specific id, which obsiously redirects to specified page but not dynamic. Any help or assitance regarding the topic would be trully appriciated. views.py from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from django.core.urlresolvers import reverse class CommentUpdate(UpdateView): model = Comment fields = ['comment_body'] def get_success_url(self): return reverse('detail', args=(2,)) #how to make this part dynamic example of detail view. class DetailsView(generic.DetailView): model = Product template_name = 'details.html' urls.py (just in case) url(r'^(?P<pk>[0-9]+)/$', views.DetailsView.as_view(), name="detail"), url(r'review/(?P<pk>[0-9]+)/$',views.CommentUpdate.as_view(), name="comment-update"), -
C:\Python3.6.3\python manage.py runserver is not responding correctly
C:\Python3.6.3\python manage.py runserver is not responding correctly. I checked the references and documents both python and Django is installed correctly. -
django.db.utils.IntegrityError: (1048, "Column 'category_type' cannot be null")
goods.py class Goods(models.Model): category = models.ForeignKey(GoodsCategory, verbose_name='xxx') goods_sn = models.CharField(default='', max_length=50, verbose_name='xxx') name = models.CharField(max_length=300, verbose_name='xxx') click_num = models.IntegerField(default=0, verbose_name='xxx') sold_num = models.IntegerField(default=0, verbose_name='xxx') GoodsCategory.py class GoodsCategory(models.Model): CATEGORY_TYPE = ( (1, "Level 1"), (2, "Level 2"), (3, "Level 3"), ) name = models.CharField(default="", max_length=30, verbose_name="Category name", help_text="Category name") code = models.CharField(default="", max_length=30) desc = models.TextField(default="", verbose_name="describe") category_type = models.IntegerField(choices=CATEGORY_TYPE, verbose_name="Category Level", help_text="Category Leve") parent_category = models.ForeignKey("self", null=True, blank=True, related_name="sub_cat") is_tab = models.BooleanField(default=False) add_time = models.DateTimeField(default=datetime.now) import_goods_data.py for goods_detail in row_data: goods = Goods() goods.name = goods_detail["name"] goods.market_price = float(int(goods_detail["market_price"].replace("¥", "").replace("$", ""))) goods.shop_price = float(int(goods_detail["sale_price"].replace("¥", "").replace("$", ""))) goods.goods_brief = goods_detail["desc"] if goods_detail["desc"] is not None else "" goods.goods_desc = goods_detail["goods_desc"] if goods_detail["goods_desc"] is not None else "" goods.goods_front_image = goods_detail["images"][0] if goods_detail["images"] else "" category_name = goods_detail["categorys"][-1] categories = GoodsCategory.objects.filter(name=category_name) if categories.exists(): category = categories[0] else: category = GoodsCategory.objects.create(name=category_name) goods.category = category goods.save() When I run this script, I get this error: django.db.utils.IntegrityError: (1048, "Column 'category_type' cannot be null") I have tried many times and still haven't solved this problem. Can you help me? -
python virtualenv os.py not found although exists in system wide
With virtualenv version 1.10.1 I've created /var/www/vhosts/example.com/django-app-env/ and lib64 point to lib within the /lib/python2.7 directory os.py points at /usr/lib64/python2.7/os.py which exists. However, passenger reports File "/var/www/vhosts/example.com/django-app-env/lib64/python2.7/os.py", line 312, in execl execv(file, args) OSError: [Errno 2] No such file or directory Its Python 2.7.5 Why? -
How to properly set a django secret key on a gandi simple instance?
I think the question is quite descriptive of my problem, but I will set the whole story anyway. I have a website ready for production. I tested it with clear secret key set in the settings.py file, exactly as it is said not to, with a big warning :) Now that I’m sure that the website works correctly, I’m trying to find a way to deploy it again, with hidden secret key, but I don’t know how. I tested locally, with secret key set as environment variable, but it does not work on the gandi instance. Is it possible to set environment variables on gandi’s simple instance ? Is there some other proper ways to hide that key ? Thanks for your answers. -
Django model - how to go about this concept
I have a product model with the following: class Product(models.Model): name = models.CharField(max_length=255) handle = models.CharField(max_length=55) summary = models.CharField(max_length=255, blank=True) category = models.ForeignKey(Category) Above is just the product detail, but there are 3 types of pricing: Standard - normal regular pricing by filling the price field Variant - pricing with product variants (size, colour, etc.) with their respective prices Combined - this is a combination of other saved products, with a custom price provided by user. For 1 and 2 I have the below model. If the product model has more than 1 price on StandardProduct model then I know it has variants. class StandardProduct(models.Model): variant_type = models.CharField(max_length=55) variant_name = models.CharField(max_lenght=55) product = models.ForeignKey(Product) sku = models.CharField(max_length=55, blank=True, null=True) barcode = models.CharField(max_length=55, blank=True, null=True) selling_price = models.DecimalField(max_length=15, decimal_places=2) How do I go about creating the CombinedProduct model? The combined product model can have different created products inside (with their quantities). The price is specified by the user. Below is what I have, but I don't know how to approach this. class CombinedProduct(models.Model): product = models.ForeignKey(Product) item = models.ForeignKey(StandardProduct) quantity = models.DecimalField(max_length=15, decimal_places=2) -
Only return the value instead of {'this' : 5} in Django
Sorry for the unclear title. Here is my joueur.py def vie_pourcentage_user (self): viepourcentageuser = (self.user.profile.vie * 100) / self.user.profile.vie_max return {'viepourcentageuser': int(viepourcentageuser)} def energie_pourcentage_user (self): energiepourcentageuser = (self.user.profile.energie * 100) / self.user.profile.energie_max return {'viepourcentageuser': int(energiepourcentageuser)} Here is my view.py def index(request): viepourcentageuser = joueur.vie_pourcentage_user(request) energiepourcentageuser = joueur.energie_pourcentage_user(request) return render(request, 'base.html', { 'viepourcentageuser': viepourcentageuser, 'energiepourcentageuser': energiepourcentageuser, }) Here is what I see : {'viepourcentageuser': 100} Here is what I would like to see : 100 Sorry I know this is basics but it seemed like I missed something. Thanks ! -
How eliminate selection in ManytoMany form field
I have this model: class Transaction(models.Model): date = models.DateTimeField(auto_now_add=True) buyer = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="buyer") smokers = models.ManyToManyField(UserProfile) price = models.FloatField(blank=True) And have this form: class TransactionForm(ModelForm): class Meta: model = Transaction fields = ['smokers', 'price',] I would like to access smokers field and eliminate few options (that user won't be able to select it or even see it in HTML). Is that even possible? -
How to get prerequisites for gettingstartedwithdjango.com tutorial?
I'm following the tutorial "Getting Started With Django" on gettingstartedwithdjango.com. I'm at the prerequisites on a VM that runs Precise64. The maker supplies a shell script named postinstall.sh. Executing that, it tries to install, among others, ruby1.8.7 but fails to download it. After that it wants to install net-ssh-gateway, mime-types, chef and puppet, which all fail, because they need ruby2.0 or 2.2. So i've done "apt get install ruby", which got me ruby1.8. I've tried to get a newer version, but it couldn't be found. When I run the script again it still fails to install the apps, that need ruby. And installing them via "apt get install" only works for puppy, the others are unknown. I would love to do the tutorial, but I fear this applications or libraries are needed. So how do I get those libraries/applications installed? -
site-packages and organizing a multi-app django environment to make sense of templates
I am trying to figure out the best and most logical way to install multiple Django apps and have them organized. In actual fact, I am trying to make sure that my templates are inheriting in the right manner but first off I thought perhaps some Django gurus can let me know what is the best way to organize a multi-app Django site. Starting off, I have used Wagtail as my core installation first and then decided to install more apps from there. Basically, on top of Wagtail, I have decided to install puput following their instructions from https://puput.readthedocs.io/en/latest/setup.html#installation-on-top-of-wagtail pip install puput And at the same time in the same virtualenv I also installed the blog app thru python manage.py startapp blog from this very good tutorial from here. So basically I have both these apps in my INSTALLED_APPS settings but puput is in site-packages whereas the blog app resides in the folder beside where manage.py is. So I was wondering should I move puput to the same directory such that PROJECT_DIR |-blog/ |-puput/ |-mysite/ |--|-settings/ |--|-templates/ |--|-urls.py |--|-etc |-manage.py |-etc The main reason I am asking this is because I am trying to figure out the best way people … -
Displaying images in html - Django
I have a little problem, and I dont have idea why my project doesn't work how I want. I have a models.py class Strona(models.Model): title = models.CharField(max_length=250, verbose_name="Tytuł", help_text="Podaj tytuł artykułu") slug = models.SlugField(unique=True, verbose_name="Adres url SEO", help_text="Automatycznie tworzony przyjazny adres URL") content = HTMLField(verbose_name="Treść artykułu", help_text="Wypełnij treścią artykułu") image = models.FileField(upload_to='blog_images',verbose_name="Obrazek", help_text="Załącz obraz") and in view.py I have from django.shortcuts import render from .models import Strona def strona_glowna(request): strona_glowna = Strona.objects.all() context = {'strona_glowna': strona_glowna} return render(request, 'strona/index.html', context=context) After that I've create the html file and include inside a code : ... {% for strona in strona_glowna %} <strong>{{strona.title}}</strong><br> {% if strona.image == True %} <img src="{{strona.image.url}}"><br> {% else %} {% endif %} <p>{{strona.content|safe}}<p></p> {% endfor %} ... in setting.py I declared: STATIC_URL = '/static/' MEDIA_URL = '/media/' And the problem is, when I reload a website the images doesn't show. I think the routing for upload is ok, but I don't know why I can't display the images. Any ideas? -
Unknown field error in django
I am trying to follow a tutorial and i get this error when i run makemigrations, however in the tutorial, they dont get the error. here is the tutorial: https://www.codingforentrepreneurs.com/blog/how-to-create-a-custom-django-user-model/ This is the error i get at 24:59 in the video: django.core.exceptions.FieldError: Unknown field(s) (username) specified for CustomUser. Here is full traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/base.py", line 327, in execute self.check() File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/importlib/__init … -
How to correctly run a form to both create and edit existing data models in Django, with file upload?
OK, I've had a lot of trouble getting this to work. I'm trying to design webform that people can use to submit an application, but also later edit the application. Ended up not using FormWizard, it just wasn't working for me. This function basically works, but I think I did something wrong that is triggering the validation script. All of my required fields have a "This field is required." I am also getting the same error when I try to upload a file (not on page load, on form submit), I'm not sure if these are related. Any suggestions how to get this functioning properly? Here is my view.py for the standard form def app1(request): if request.method == 'POST': form = ChildInfoForm(request.POST) if form.is_valid(): childinfo = form.save(commit=False) childinfo.user = request.user try: childinfoid = ChildInfo.objects.get(user=request.user).id except ObjectDoesNotExist: childinfoid = None if childinfoid: childinfo.id = childinfoid childinfo.save() return redirect('app2') else: try: childinfo = ChildInfo.objects.get(user=request.user) except ObjectDoesNotExist: childinfo = ChildInfo(user=request.user) #childinfo.save() form = ChildInfoForm(model_to_dict(childinfo)) return render(request, 'registration/step1.html', {'form': form}) Here's my view for the upload file function: def app7(request): if request.method == 'POST': form = MortgageUploadForm(request.POST, request.FILES) if form.is_valid(): form = form.save(commit=False) form.user = request.user form.save() return redirect('upload_success') else: form = MortgageUploadForm() return … -
Django CBV - get url variable for use in class, error self s not defined
I am passing and trying to use site_id in my add form. I want to pre fill and hide the site_data field with the site ID in the url. and then use that variable to pass some more information to the context too. my CBV is as such: class AddSubnet(CreateView): model = SiteSubnets template_name = "sites/edit_subnet.html" fields = ['device_data', 'site_data', 'subnet', 'subnet_type', 'circuit', 'vlan_id', 'peer_desc'] site_id = self.kwargs['site_id'] site = get_object_or_404(SiteData, pk=site_id) @method_decorator(user_passes_test(lambda u: u.has_perm('config.add_subnet'))) def dispatch(self, *args, **kwargs): return super(AddSubnet, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("sites:site_detail_subnets", args = (site_id,)) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['SiteID']=site_id context['SiteName']=site.location context['active_subnets']='class="active"' # return context this currently yields with: File "/itapp/itapp/sites/urls.py", line 2, in <module> from . import views File "/itapp/itapp/sites/views.py", line 984, in <module> class AddSubnet(CreateView): File "/itapp/itapp/sites/views.py", line 988, in AddSubnet site_id = self.kwargs['site_id'] NameError: name 'self' is not defined -
Django: set foreignkey to model of which `abstract` True...?
I've designed some model structures in django: class Symbol(BaseModel): field1 = models.CharField(max_length=50) class Meta: abstract = True class DetailSymbol1(Symbol): field2 = models.CharField(max_length=50) class DailyData(BaseModel): symbol = models.ForeignKey(DetailSymbol1) field3 = models.CharField(max_length=50) After makemigrations and migrate done, I created some model objects: In [1]: a = DetailSymbol1.objects.create(field1="a", field2="b") In [2]: a.dailydata_set.create(field3="c") Out[2]: <DailyData: DailyData object> In [3]: a.dailydata_set.create(field3="d") Out[3]: <DailyData: DailyData object> In [4]: DailyData.objects.count() Out[4]: 2 Now, What I want to do is to make Symbol model NOT abstract model and make DailyData have ForeignKey to Symbol, not DetailSymbol1. Here is the final code: class Symbol(BaseModel): field1 = models.CharField(max_length=50) class DetailSymbol1(Symbol): field2 = models.CharField(max_length=50) class DailyData(BaseModel): symbol = models.ForeignKey(Symbol) field3 = models.CharField(max_length=50) When I tried to migration, this prompt occured: You are trying to add a non-nullable field 'symbol_ptr' to detailsymbol1 without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: I have no idea what should I do with this message. How can I deal with it without … -
Response a json type longitude and latitude using Google geocoding API in django using Python
I am a newcomer to Django programming. Here I am working on the server side. The thing I want to do is when client-side type a location in a string, the server will response a longitude and latitude using the geocoding API. But the problem is I can't even successfully import 'google maps' or 'django_google_maps' API in the visual studio How can I import them successfully and apply them to my server-side code? Thank you for answering