Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Starting a MQTT service in INIT prevents me from loading models with "Apps aren't loaded yet." error. Where can I start it?
I'm brand new to Django and Python, and not sure how to get around this problem, but I know what's wrong and why... I'm connecting to a MQTT broker (internet of things messaging protocol / provider) so I can update a webpage with data from some sensors I have. I've started the MQTT service in my init as was suggested below, but I don't know enough to know if that's right or wrong, but it works. https://stackoverflow.com/a/41017210/2408033 My problem happens, when I want to try to update my database with the messages I receive from the MQTT broker. I need to import my model so I can update it, but the model hasn't been loaded yet, and it throws the error - "Apps aren't loaded yet." I was reading that you shouldn't attempt to import models before the Django setup has run (which is after init) so I'm not sure where / how to start the loop for the MQTT broker thread? Where else can I place the code to start the loop where it won't be triggered a second time? -
Django error in creating model
I'm having an issue with creating a user profile with a foreign object. I have a user and I want to attach an account type to that user. model.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) account = models.ForeignKey(Account, unique=True) class Account(models.Model): reports = models.IntegerField(default=3) accounttype = models.CharField(default='Free', max_length=250) description = models.CharField(default='N/A', max_length=250) monthlycost = models.FloatField(default=0.0) def __str__(self): return self.user.username + " - " + self.accounttype The issue is I'm getting the below error: account = models.ForeignKey(Account, unique=True) NameError: name 'Account' is not defined How do I call the Account class for the foreign key? -
Django Integrity Error "Column 'section_id' cannot be null"
I have seen many questions regarding this error in Django, but I'm at a loss because as far as I can tell, no table in my database has a section_id column. I get the error when a user attempts to register and views.py attempts to create a user. I recently changed the "Profile" model (Profile objects are automatically created alongside User objects) in my application to have a section attribute rather than a section_id attribute, but I reset the migrations and recreated the database several times. I'm thinking that it may be an issue with making the migrations, but I really have no idea. Here is the profile model that used to have a section_id attribute: class Profile(models.Model): """ An extension of the built-in Django user model to allow for the different types of users """ USER_TYPES = ( ('S', 'Student'), ('I', 'Instructor'), ('C', 'Client') ) user = models.OneToOneField(User, on_delete=models.CASCADE) user_type = models.CharField(max_length=1, choices=USER_TYPES) section = models.ForeignKey(Section, default=None) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): if instance.is_staff != 1: instance.profile.save() And here is the code that is raising the error: new_user = User.objects.create_user(email, email=email, password=password) -
How to display a error message to the user by redirecting to current page - django
I have a question that I feel like I solved before but for some reason, I just cant figure it out. I have a django view that will update a users informaiotn that is stored in the data base that involves the user entering his current password, a new password, and verification of the new password. I have the processing complete fo rthe situation where the user enters all of the correct information. I am not trying to add hte else statements just in case the user does not enter the current existing password or the passwords dont match. In the two commented lines in the else statements is where I want display the current html template with the form and have a message that displays a message that is assigned for different errors that exist. if 'passwordSubmit' in request.POST: updatePassword = updatePasswordForm(request.POST) if updatePassword.is_valid(): cd = updatePassword.cleaned_data old_password = cd['old_password'] new_password = cd['new_password'] verify_password = cd['verify_password'] user = authenticate(username=currentUser.username, password=old_password) if user is not None: if new_password == verify_password: secure_password = make_password(new_password) update_user = currentUser update_user.password = secured_password update_user.save() else: message = 'The two passwords do not match' # if the passwords do no match else: message = 'The … -
How to squash Django migrations with lazy references?
I have a Django 1.11 project and I'm trying to squash all migrations by deleting and re-making all of them. However, when I go to run manage.py makemigrations I get an error like: ValueError: The field app1.Model1.campaign was declared with a lazy reference to 'app2.Campaign', but app 'app2' isn't installed. However, app2 is definitely installed. I even print out my INSTALLED_APPS list in my settings.py to confirm it is. What's causing this error? -
Django file upload and creating directories
I am trying to implement dropbox application using django. I completed with user login,signup part . Also with with some authentications. Now i want to implement file uploads , creating directories and sharing files with users. Also preview of uploaded files for respective user. Right now i have extended user model for setting user. I have not written any model. How should i proceed further? a new model is necessary for this application? thanks in advance -
Django models to have a shared calculated field
I have 3 Django models that shared a few common attributes and then they have lot of other attributes that make them different. Example: Model1 quality_score other attributes specific to Model1 Model2 quality_score other attributes specific to Model2 Model3 quality_score other attributes specific to Model3 I need to create a calculated field like this: def _get_quality_band(self): if self.quality_score is None: return '' elif self.quality_score > 0 and self.quality_score <= 10: return 'bad' elif self.quality_score > 10 and self.quality_score <= 19: return 'average' elif self.quality_score > 19 and self.quality_score <= 28: return 'good' else: return '' quality_band = property(_get_quality_band) Is there a way to make the 3 models share this property instead creating it in every model? Appreciate the help. -
Invalidate browser cache for static files in Django
In Django we have ManifestStaticFilesStorage for caching static files, but it works between Django and browser, but I want right cache between user and browser. I want: every time static file is changed, hash of file is recalculated and browser cache is invalidated and user see new static file without F5 adn without running --collectstatic --no-input. My code now isn't working: settings.py STATICFILES_STORAGE = 'auth.utils.HashPathStaticFilesStorage' CACHES = { 'staticfiles': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'staticfiles', 'TIMEOUT': 3600 * 24 * 7, 'MAX_ENTRIES': 100, } } and auth.utils.py: # -*- coding: utf-8 -*- import time from hashlib import sha384 from django.conf import settings from django.core.cache import cache from django.contrib.staticfiles.storage import ManifestStaticFilesStorage try: ACCURACY = settings.STATICFILES_HASH_ACCURACY except AttributeError: ACCURACY = 12 try: KEY_PREFIX = settings.STATICFILES_HASH_KEY_PREFIX except AttributeError: KEY_PREFIX = 'staticfiles_hash' class HashPathStaticFilesStorage(ManifestStaticFilesStorage): """A static file storage that returns a unique url based on the contents of the file. When a static file is changed the url will also change, forcing all browsers to download the new version of the file. The uniqueness of the url is a GET parameter added to the end of it. It contains the first 12 characters of the SHA3 sum of the contents of the file. Example: {% … -
Python subprocess behaves different when called from Django vs unit test
My first time posting - please go easy on me. I could not come up with a succinct title that summarizes this issue. I seem to have a codec problem. My django-based website calls a subprocess (soffice) to convert uploaded documents to basic text files, to then go on to do some processing of the text from the doc. This was working beautifully for a time. On my local dev machine, the unit tests for file conversion still work perfect as does the complete django app, end-to-end. On the production server, where it all used to work, the file conversion call no longer works the same from within the django app, while it does work properly when run from the test code. This change in behavior appears to be the result of running general server updates. args = ['soffice', '--headless', '--convert-to', 'txt:Text', '--outdir', outDir, filePath] subprocess.call(args) fo = open(textFilePath, "r") try: docText = fo.read() except: print("Failed to read", textFilePath) docText = None I removed some of the error checking to simplify a bit. When I run the file conversion code as part of the complete django application on the production server, I can see that certain special characters such as … -
how do I delay and get after a return with celery and django?
Currently trying to clean how celery works with django which was told can work asynchronous I have run the simple celery task which works fine following the documentation so I do believe I have celery installed and running fine. But somehow I am not sure how it can work and run after a return for example I have this as to create a new user task @app.task def new_user(first, last, table): user = UserProfile() user.first_name = first user.last_name = last user.table = table user.save() return user I have a post api call just to make it as a sample on how celery works. I have this in my view class List(View): def post(self, request): all_users = UserMQS().profile() output = [] for user in all_users: output.append({ 'id': user.id, 'first_name': user.first_name, 'last_name': user.last_name }) ns = new_user.s('First Name1', 'Last Name1', "Table1") res = ns.delay() return JsonResponse(output, safe=False) res.get() I also tried something like new_user.delay('First Name1', 'Last Name1', "Table1") but doesn't work though. Can someone give me an idea how this can be done? I want the return JsonResponse to be running WHILE new_user is created. This isn't just for creating new_user I am just doing it to test how celery works so … -
Django mysql setup error on mac os [duplicate]
This question already has an answer here: Python3.4 can't install mysql-python 4 answers ]mitwas-MacBook-Air:mytestsite Mitwa$ pip3 install MYSQL-python Collecting MYSQL-python Using cached MySQL-python-1.2.5.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/9l/9zjr811503367lfnybnyqlqc0000gn/T/pip-build-fk08ytxi/MYSQL-python/setup.py", line 13, in <module> from setup_posix import get_config File "/private/var/folders/9l/9zjr811503367lfnybnyqlqc0000gn/T/pip-build-fk08ytxi/MYSQL-python/setup_posix.py", line 2, in from ConfigParser import SafeConfigParser ImportError: No module named 'ConfigParser' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/9l/9zjr811503367lfnybnyqlqc0000gn/T/pip-build-fk08ytxi/MYSQL-python/ I am getting this error while setting up Django MYSQL for python. Anyone have idea how to solve it? -
Removing a single item from Django cart
trying to create a shopping cart application and currently stuck trying to remove a single item from a cart. I can't seem to work out how to remove a single product as currently it removes all of a product ID using the remove function. This is cart.py file: from decimal import Decimal from django.conf import settings from shop.models import Product class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def __len__(self): """ Count all items in the cart. """ return sum(item['quantity'] for item in self.cart.values()) def __iter__(self): """ Iterate over the items in the cart and get the products from the database. """ product_ids = self.cart.keys() # get the product objects and add them to the cart products = Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)]['product'] = product for item in self.cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item def add(self, product, quantity=1, update_quantity=False): """ Add a product to the cart or update its quantity. """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: … -
Django templates: make child loop inside of a nested loop to do certain number of iterations
I have two lists: list1 = ['a','b','c','d'] list2 = [1,2,3,4,5,6,7,8,9,10,11,12] I want to render them into the template as follows: a 1 2 3 b 4 5 6 c 7 8 9 d 10 11 12 So the first column with the letters (list1) is row indexes. Each row consists of 3 cells populated from list2. Template structure is the following: <div class="row"> <div class="row-index">row index from list1</div> <div class="cell">cell1 from list2</div> <div class="cell">cell2 from list2</div> <div class="cell">cell3 from list2</div> </div> Obviously it is not enough to do a simple nested nested loop here (for list1 and list2): {% for row_index in list1 %} <div class="row"> <div class="row-index">{{ row_index }}</div> {% for cell in list2 %} <div class="cell">{{ cell }}</div> {% endfor %} </div> {% endfor %} This will render 4 rows (which is right!) but each row will have 12 cells instead of 3 per row. Unfortunately, zip_longest(list1, list2) won't help since it adds extra 'None' elements to list1 to make it of equal length with list2. Result is 4 actual row indexes, followed by 8 empty ones. And the cells rendered are all the same for each individual row, e.g. "a 1 1 1", "b 2 2 2", … -
Update for Serializers with many=True only create is supported in django api
I am using many in my serializer for creating new fields . I need to implement update in order to add the new fields coming and leave the existing ones as it is. Mycode is given below. models.py class Device(models.Model): device_id = models.CharField(max_length=200) auth_token = models.CharField(max_length=100) class ThirdPartyApps(models.Model): auth_token = models.ForeignKey(Device, on_delete=models.CASCADE) app_name = models.CharField(max_length=100) serializers.py class AppSerializer(serializers.ModelSerializer): class Meta: model = Apps fields = ('app_name', 'auth_token_id') def create(self, validated_data): if "auth_token_id" in self.context: id1 = self.context["auth_token_id"] instance = self.Meta.model(**validated_data) user_id = id1 if user_id is not None: instance.auth_token_id = user_id instance.save() return instance views.py @api_view(['POST']) def add_apps(request): data = request.data auth_token = request.META.get('HTTP_AUTHTOKEN', '') auth_tok = Device.objects.get(auth_token=auth_token) a_id = auth_tok.id serializer = AppSerializer(ThirdPartyApps, data=data, context={"auth_token_id": a_id}, many=True) if serializer.is_valid(): serializer.save() content = collections.OrderedDict( [('status', True), ('message', "Third party apps are saved")]) return Response(content, status=status.HTTP_200_OK) else: return Response(serializer.errors) I tried to use the update support of django by giving the model name while passing it to serializer to call the update method. But it says that when many=True , update is not supported only create method is supported . It is suggesting to use a ListSerializer class and override `.update() in my serializers. I am unable to understand how to … -
Default/logical directory structure for Django
I have gone through a number of tutorials, built a few apps, and even read the book by one of the creators of Django. But I am mystified by the 'proper' directory structure. One always seems to get a tree that looks like this (with a virtual environment at the top): venvdir | +---manage.py | +---mysitedir | +--settings.py | +--urls.p | +--staticfiles (where collectstatic puts everything) | +---myapp1dir | +--views.py | +--models.py | +--staticdir | +---static-objects-tree... What I find confusing is that os.path.abspath(__file__) points to 'mysitedir' (the references say it always points to the dir with settings.py in it). Presumably the idea is that a whole 'site' has one or more 'apps' under it, though I have never seen that done as such. First, is that correct? Second, is there some compelling reason (or am I doing it wrong) such that the 'apps' don't slot in below 'mysitedir'? That would seem to make more sense and maintain modularity. It seems odd the way Django does things like going through the whole tree looking for static files. It also seems illogical that you list the 'apps' in settings.py, and - once again - Django needs to go traversing up and back … -
I am attempting to add a field to my model that allows for multiple photos to be uploaded at once but they do not show up in the admin or my form
I am trying to add functionality to be able to upload multiple "products" at once to a model. Each needs to have a picture, price, and description and will have a many to one relationship to a "Partner". I know that formsets are the way to go but I can't seem to get the implementation correct. When I migrate, I can see that the Products class is created but it doesn't show up in the admin. Here is my views.py file def partner_create(request): ProductFormSet = modelformset_factory(Products, form=ProductsForm, extra=3) if request.method == 'POST': partnerForm = PartnerForm(request.POST) formset = ProductFormSet(request.POST, request.FILES, queryset=Products.objects.none()) if partnerForm.is_valid() and formset.is_valid(): partnerForm = partnerForm.save(commit=False) partnerForm.user = request.user partnerForm.save() for form in formset.cleaned_data: image = form['image'] photo = Images(partner=partnerForm, image=image) photo.save() messages.success(request, "Successfully Created") return HttpResponseRedirect("/") else: print partnerForm.errors, partnerForm.errors else: partnerForm = PartnerForm() formset = ProductFormSet(queryset=Products.objects.none()) return render(request, 'partner_form.html', {'partnerForm': partnerForm, 'formset': formset}, context_instance=RequestContext(request)) Here is my models.py file: class Partner(models.Model): name = models.CharField(max_length=120) logo = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") banner_image = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") mission = models.TextField() vision = models.TextField() height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) # text = models.TextField() website_link = models.CharField(max_length=120) fb_link = models.CharField(max_length=120) twitter_link = models.CharField(max_length=120) ig_link = models.CharField(max_length=120) slug … -
Django Python str() argument 2 must be str, not int
I have a 12x12 dictionary with values, which are 0 for all. matchfield = {} for i in range(12): for j in range(12): matchfield[str((i, j))] = 0 I want to set some values to 1 with the following snippet (it checks whether the surrounding fields are free): length = 4 m = randint(1, 10-length) n = randint(1, 10) for x in range(m-1, m+length+1): for y in range(n-1, n+1): if not matchfield[str((x, y))]: for k in range(length): matchfield[str((m+k, n))] = 1 if I test this in python console, all works and the 4 selected values are set to 1, but in my Django view function I got an TypeError on the following line: matchfield[str((m+k, n))] = 1 Environment: Request Method: GET Request URL: https://www.maik-kusmat.de/schiffeversenken/start/ Django Version: 1.11.5 Python Version: 3.5.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'accounts', 'home', 'contact', 'kopfrechnen', 'braces', 'ckeditor', 'ckeditor_uploader', 'battleship', 'hangman'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware'] Traceback: File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/home/pi/Dev/mkenergy/src/battleship/views.py" in battleship_start … -
django delete object with html button
I have a simple site project in Django and I have movies lists in man page and movies details in the second page. I want to add a delete button on movies details tab where user can delete the movies object. views.py def movies_list(request): return render(request, 'dataset.html',{'movies':movies.objects.all()}) def movies_details(request,slug): movies_details=MyModel.objects.all() det=get_object_or_404(movies_details, slug_name=slug) return render(request, 'dataset_details.html',{'movies_details':movies_details,'det':det}) what is the better method to do that ? something like this using new view : def delete(request, id): note = get_object_or_404(Note, pk=id).delete() return HttpResponseRedirect(reverse('movies_details.views.movies_details')) urls.py url(r'^delete/(?P<id>\d+)/$','project.app.views.delete'), or some like this ? if request.POST.get('delete'): obj.delete() or use some Django form ? -
Django Form Returning Invalid
I'm trying to implement a form that has checkbox options for a field, and a user can select multiple checkboxes for that specific field in the form and all the check-marked values should be sent in the POST request. But views.py is saying that the form is invalid when I try to submit the form. The reason it is invalid is this Select a valid choice. [&#39;top&#39;, &#39;mid&#39;] is not one of the available choices. I get a similar error when I only select one checkbox. Here is my partial models.py from django.db import models LEAGUE_ROLES = ( ('top','Top'), ('mid','Mid'), ('jungle','Jungle'), ('bottom','Bottom/ADC'), ('support','Support'), ) class CreatePosting(models.Model) createPostingOpenRoles = models.CharField(max_length = 10, choices=LEAGUE_ROLES, default=None) def __str__(self): # __unicode__ on Python 2 return self.title Here is my partial forms.py class TeamPostingCreateForm(ModelForm): class Meta: model = CreatePosting widgets = { 'createPostingOpenRoles': forms.CheckboxSelectMultiple(), } fields = '__all__' def __init__(self, *args, **kwargs): super(TeamPostingCreateForm, self).__init__(*args, **kwargs) Here is my partial views.py def createposting(request): UserTeamPostingCreateForm = TeamPostingCreateForm() if request.method == "POST": UserTeamPostingCreateForm = TeamPostingCreateForm(request.POST) if UserTeamPostingCreateForm.is_valid(): logger.error("valid form") else: #print form error logger.error(UserTeamPostingCreateForm.errors) variables = { 'form': UserTeamPostingCreateForm } return render(request, 'createposting.html', variables) And in my template, I have this for the form field {{ form.createPostingOpenRoles }} … -
Cant save form data in data base -Django
I am trying to create a simple form which takes name and email as user input. But after I submit,its not getting saved in database manage.py dumpdata shows [] i.e empty row. Please help! models.py class EmpD(models.Model): name = models.CharField(max_length=100) email=models.CharField(max_length=100) forms.py class SubmitF(forms.ModelForm): name = forms.CharField() email= forms.CharField() class Meta: model = EmpD fileds = '_all_' views.py def get(self, request): form= SubmitF() return render(request, 'emp/home.html', {'form': form}) def post(request): if request.method == 'POST': form = SubmitF(request.POST) if form.is_valid(): obj = EmpD() obj.name = form.cleaned_data['name'] obj.email = form.cleaned_data['email'] obj.save() return render(request, self.template_name,{'form':form}) def index(request): return render(request, 'emp/home.html') html containing form: <form action='' method="post" > {% csrf_token %} {{ form }} <table border="0" cellpadding="5" cellspacing="0"> <tr> <td style="width: 50%"> <label for="Name"><b>First name *</b></label><br /> <input name="Name" type="text" maxlength="50" style="width: 260px" /> </td> <td style="width: 50%"> </td> </tr> <tr> <td colspan="2"> <label for="Email_Address"><b>Email *</b></label><br /> <input name="Email_Address" type="text" maxlength="100" style="width: 535px" /> </td> </tr> <tr> <td colspan="2"> <input type="submit" value="Submit Data" /> </td> </tr> </table> </form> -
What types of requests make good candidate for `@transaction.non_atomic_requests`?
A common way to handle transactions on the web is to wrap each request in a transaction. In Django, you can set ATOMIC_REQUESTS to True in the configuration of each database for which you want to enable this behavior. It works like this. Before calling a view function, Django starts a transaction. If the response is produced without problems, Django commits the transaction. If the view produces an exception, Django rolls back the transaction. While the simplicity of this transaction model is appealing, it also makes it inefficient when traffic increases. Opening a transaction for every view has some overhead. For requests that do not need to be wrapped in transactions, you can apply the @transaction.non_atomic_requests decorator. Given a Django view.py with several View classes and request methods. How might I go about deciding which requests would make good candidates for the non-atomic decorator? What "gotchas" might be lurking? I could see POST methods not making good candidates or anything with a .save(), but what else should I look out for? -
how to access data from extended user model django
Been through as many of the examples on here and I cannot find a solution. I have extended the Django user model, I have login and saving working fine. However I cannot retrieve the additional user information that I want to display on a profile page. See code below: views.py - Registration form. class UserFormView(View): form_class = UserForm template_name = 'crw/reg_form.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] password = form.cleaned_data['password'] email = form.cleaned_data['email'] user.set_password(password) user.save() user_profile = freelanceUser(user=user, contactNum=form.cleaned_data['contactNum'], jobTitle=form.cleaned_data['jobTitle'], homeLoc=form.cleaned_data['homeLoc'], startRate=form.cleaned_data['startRate']) user_profile.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('crw:profile') return render(request, self.template_name, {'form': form}) User Profile View: class UserDetail(generic.ListView): context_object_name = 'object_list' template_name = 'crw/profile.html' def get_queryset(self): return self.request.user @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) Models.py class freelanceUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) contactNum = models.CharField(max_length=100) jobTitle = models.CharField(max_length=100) homeLoc = models.CharField(max_length=100) startRate = models.CharField(max_length=100) profile.html {% extends "crw/base.html" %} {% block body %} <section class="detail-section"> <div class="row"> <div class="small-8 small-centered colum"> <h1>Welcome: {{ object_list.first_name }} {{ object_list.last_name }}</h1> <p>We have the following information stored … -
I can not connect laravel as django is already in my pc
I installed django on my pc.but i want to instal laravel also.but my localhost didn't connect.Whenever i want to connect laravel in localhost it gives error like "Laravel development server started: [Thu Oct 5 01:41:01 2017] Failed to listen on 127.0.0.1:8000 (reason: An attempt was made to access a socket in a way forbidden by its access permissions." .Please give me solution .thanks -
Import Error on Flask Blueprint
I am attempting to build a simple CRUD webapp in Python using Flask and Flask-Blueprint(following this tutorial: https://scotch.io/tutorials/build-a-crud-web-app-with-python-and-flask-part-one) (I am using python 3.6.1 and attempting to translate the post from python 2.7) When I try to run the app right now I get the following error: File "/anaconda/lib/python3.6/site-packages/flask/cli.py", line 90, in locate_app import(module) File "/Users/gordonread/Dropbox/Programs/InventoryServer/run.py", line 6, in app = create_app(config_name) File "/Users/gordonread/Dropbox/Programs/InventoryServer/app/init.py", line 38, in create_app from .auth import auth as auth_blueprint ImportError: cannot import name 'auth' Here is the code causing the problem: def create_app(config_name): #other code from .admin import admin as admin_blueprint app.register_blueprint(admin_blueprint, url_prefix='/admin') from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) from .home import home as home_blueprint app.register_blueprint(home_blueprint) return app Here is the code I am trying to import: from flask import Blueprint admin = Blueprint('auth', __name__) from . import views And finally here is the relevant file structure: └───inventory ├── app │ ├── __init__.py │ ├── admin │ │ ├── __init__.py │ │ ├── forms.py │ │ └── views.py │ ├── auth │ │ ├── __init__.py │ │ ├── forms.py │ │ └── views.py │ ├── home │ │ ├── __init__.py │ │ └── views.py │ ├── models.py │ ├── static │ └── templates ├── config.py … -
pass field value to a function .extra()
After trying for hours, I am coming here. I have the following model: class Items(models.Model): date=models.DateField() giver=models.IntegerField() Class Givers(models.Model): name=models.CharField(max_length=25) Basically, an item could be given by donators from Givers model or it could be bought by user. If given, giver field stores id from Givers model. Else, it is 0. Now I want a query that will list out my items. If giver>0, I need to show the name of the giver. I can't create relationships here. This query has brought me so close and works like a charm on literal values but I want to provide the 'giver' field instead: data=Items.objects.all().extra(select={'giver_name':giver_name(1,False)}).values('giver_name','id','date') It works like a charm even if given any number (exists or not exists). But I want to do something like this but it fails cos field is not found or undefined: data=Items.objects.all().extra(select={'giver_name':giver_name(giver,False)}).values('giver_name','id','date') giver_name is a function that accepts id of a giver and a boolean value and returns a name.