Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework Cannot assign, must be a instance error for Mac
I have a one to one field on user model for birth record table. Done the api and it work perfectly in my Window 8.1 laptop. So i send it to my friend's laptop which is a Mac book, he make migration enter the details but he got this error instead. 1: ValueError: Cannot assign "1": "BirthRecord2.userId" must be a "MyUser" instance. 2: Cannot assign "1": "BirthRecord2.userId" must be a "MyUser" instance. In my laptop, the userId field in BirthRecord have a drop down to show the list of user. But in my friend's Macbook, it doesnt have the drop down of the existing user nor does it have the arrow down of the drop down at the side. This is how it shows in my laptop: https://imgur.com/a/n22DW Now i am unsure what is the problem as it works fine on my laptop even after dropping and recreating table. Or is it just MacBook problem ? Please help me Here's my code: models.py class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender = models.CharField(max_length=6, blank=True, null=True) nric = models.CharField(max_length=9, blank=True, null=True) birthday = models.DateField(blank=True, null=True) birthTime = models.TimeField(blank=True, null=True) ethnicGroup = models.CharField(max_length=30, blank=True, null=True) mobileNo = models.IntegerField(blank=True, null=True) favoriteClinic = models.CharField(max_length=50, blank=True, null=True) … -
How to use Ssl over django-realtime
I have used the django-realtime for socket in django. But i have few problems to get the project live. How to use ssl over django-realtime? Is it necessary to run node node_modules/ishout.js/server.js over webhosting of django project? -
How to access a proxy class for Group from an user?
I have a Proxy for Group like that: from django.contrib.auth.models import Group class Role(Group): class Meta: proxy = True app_label = 'auth' @property def display_name(self): return self.name.title() And I want to access from an user, something like that with roles: my_user.groups.all() How can I access the roles from user? -
django UNIQUE constraint failed error
I have fallowing structure of database. I create ProductBidPrice class on view. Add all column has not have any problem but one column which is out_going_price and income_price. When I save the new ProductBidPrice django throw this error "UNIQUE constraint failed: sales_productbidprice.price_income_id" . I want use more than one to one realtionship. I can add and save Django Web Interface. But I can't add in the view. How can I fix this problem ? Sorry about my English. I hope explain my problem. models.py class ProductPriceHistory(BaseModel): currency = models.ForeignKey(PriceCurrency) price = models.FloatField() date = models.DateField() class Meta: abstract = True class ProductIncomePriceHistory(ProductPriceHistory): product = models.ForeignKey(Product, related_name="prices_income") def __str__(self): return "%s %s of %s" % (self.price, self.currency.name, self.product.name) class ProductOutgoingPriceHistory(ProductPriceHistory): product = models.ForeignKey(Product, related_name="prices_outgoing") def __str__(self): return "%s %s of %s" % (self.price, self.currency.name, self.product.name) class AbstractBidDirectSales(BaseModel): name = models.CharField(max_length=45) sales_date = models.DateField() customer = models.ForeignKey(Customer) class Meta: abstract = True class Bid(AbstractBidDirectSales): products = models.ManyToManyField(Product, related_name="bids", through="ProductBidPrice") def __str__(self): return "%s of %s" % (self.name, self.customer.name) class DirectSale(AbstractBidDirectSales): product = models.ManyToManyField(Product, related_name="directSales", through="ProductDirectSalesPrice") class Meta: verbose_name_plural = "DirectSales" def __str__(self): return "%s of %s" % (self.name, self.customer.name) class ProductDirectSalesPrice(BaseModel): product = models.ForeignKey(Product) directSales = models.ForeignKey(DirectSale) price_income = models.OneToOneField(ProductIncomePriceHistory) price_outgoing = … -
Django with ModWsgi and Apache not a valid application
So this is an odd problem - I'm trying to deploy Django to Apache, ModWSGI on a Mac running OSx but am running into the following error message: Target WSGI script '/Library/WebServer/local_biems/biems/wsgi.py' does not contain WSGI application Now: local_biems runs ok with python manage.py runserver with no silenced issues. So I believe my project is error free and ready for deployment. a test application local_blog runs ok with runserver AND with my virtual host configuration - so I'm assuming from this that Apache and MODWSGI are playing happily together. local_biems and local_blog are alongside each other in the /Library/WebServer/ and have identical permissions. If I update the file paths in the virtual host, restart apache and do a hard reload of the site I get the error above. WSGI files are identical. What can I try? I've tried the try/catch statement around get_wsgi_application() try: application = get_wsgi_application() print 'WSGI without exception' except Exception: print 'handling WSGI exception' # Error loading applications if 'mod_wsgi' in sys.modules: traceback.print_exc() os.kill(os.getpid(), signal.SIGINT) time.sleep(2.5) but same issue. -
django chat using socket.
I am trying to add chat function to my project follow django chat tutorial from this website https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django But, even if user type something, cannot see any chat. There is no error just doesn't work. I am not sure where should I fix to chat work well. Here's my codes. And if you can email and help me, I really appreciate. My email is bmj1219@gmail.com models.py class Room(models.Model): name = models.TextField() label = models.SlugField(unique=True) def __unicode__(self): return self.label class Message(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='messages') handle = models.TextField() message = models.TextField() timestamp = models.DateTimeField(default=timezone.now, db_index=True) def __unicode__(self): return '[{timestamp}] {handle} {message}'.format(**self.as_dict()) @property def formatted_timestamp(self): return self.timestamp.strftime('%b %-d %-I:%M %p') def as_dict(self): return {'handle': self.handle, 'message': self.message, 'timestamp': self.formatted_timestamp} view.py: def chat(request): return render(request, "prj/chat.html") def new_room(request): new_room = None while not new_room: with transaction.atomic(): l = Haikunator(adjectives=['chat']) label=l.haikunate() if Room.objects.filter(label=label).exists(): continue new_room = Room.objects.create(label=label) print("entered new_room", file=sys.stderr) return redirect(reverse('prj:chat_room', args=[label])) def chat_room(request, label): print("Why is this happening\n") room, created = Room.objects.get_or_create(label=label) messages = reversed(room.messages.order_by('-timestamp')[:50]) print("entered chat_room", file=sys.stderr) return render(request, "prj/room.html", { 'room': room, 'messages': messages, }) urls.py: app_name ='prj' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name = 'index'), url(r'^prj/create_group/', views.group_create_view, name = 'create_group'), url(r'^prj/chat/', views.chat_view.as_view(), name = 'chat'), url(r'^new/$', views.new_room, name='new_room'), … -
Django - upload image file and store the image
In my custom user model, I need a field to store user's photo profile. So, I set a field photo_profile as an ImageField in the model. Now, if I go to my register page, there will be a button to upload image. After I choose my image, the of image is shown. However, when I click submit button, the webpage is asking "the field (the one for photo) is required". Is there an other way than using a FileUploadForm to solve this problem? Thanks in advance! -
Django CMS: Is there anything like "Custom Post Types" like WordPress?
I have a lot of knowledge to WordPress, but i am new to the Django CMS Framework. I've seen that i have a "Page" section in the top admin panel. Now i want to "duplicate" this "post type" (sorry for the WordPressish-language) to a new type called "Events". In WordPress, i would call register_post_type('events', $args), but how to do it in Django CMS? I know how to add model in my models.py file - but i want to access this new model separately in my admin bar. Are there any suggestions? Thank you in advance. -
Redirect and 'field' keyword issues when retriving objects from database
I have 3 models Account,Company, and Products. Company can have multiple products, Account can have multiple Companies. class Product(Meta): company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE) class Company(Meta): account = models.ForeignKey(Account, related_name='account', on_delete=models.CASCADE) I'm using Django 2.0 new url patterns, and I defined the urls: path('dashboard/', include('accounts.urls', namespace='accounts')), in accounts urls.py path('companies/<int:pk>/', AccountCompanyDetailView.as_view(), name='detail_company'), In a CBV I'm trying to get a Product instance, if the Product doesn't exist, check if Company doesn't exist and base on the above results do a redirect. if not account: raise Http404 try: product = Product.objects.get(company__account=account, company__pk=company_pk, pk=product_pk) except Product.DoesNotExist: # try: # Company.objects.get(company__account=account, company__pk=company_pk) # except Company.DoesNotExist: # return redirect('accounts') return redirect('accounts:detail_company', pk=company_pk) return product If I use it as above (with Company code commented) when a product is wrong there is no error but redirect doesn't happen. If I un-comment the company part, I receive field error: Cannot resolve keyword 'company' into field. company is the ForeignKey on the Product Model to the Company Model. I'm doing the Company lookup after, and not before, Product lookup not to do two lookup(s) if is not necessary. -
Hosting Django Webserver on google Cloud VM
I've made a simple webserver and been running on local host but know want to transfer that to a vm. Whenever I run the command python manage.py runserver <"vm external ip address"> I receive the error code "Error: That IP address can't be assigned to" I'm extremely knew to web development and any instruction is greatly appreciated -
django chat using socket
I am trying to add chat function to my project follow django chat tutorial from this website https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django But, even if user type something, cannot see any chat. There is no error just doesn't work. I am not sure where should I fix to chat work well. models.py class Room(models.Model): name = models.TextField() label = models.SlugField(unique=True) def __unicode__(self): return self.label class Message(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='messages') handle = models.TextField() message = models.TextField() timestamp = models.DateTimeField(default=timezone.now, db_index=True) def __unicode__(self): return '[{timestamp}] {handle} {message}'.format(**self.as_dict()) @property def formatted_timestamp(self): return self.timestamp.strftime('%b %-d %-I:%M %p') def as_dict(self): return {'handle': self.handle, 'message': self.message, 'timestamp': self.formatted_timestamp} view.py: def chat(request): return render(request, "prj/chat.html") def new_room(request): new_room = None while not new_room: with transaction.atomic(): l = Haikunator(adjectives=['chat']) label=l.haikunate() if Room.objects.filter(label=label).exists(): continue new_room = Room.objects.create(label=label) print("entered new_room", file=sys.stderr) return redirect(reverse('prj:chat_room', args=[label])) def chat_room(request, label): print("Why is this happening\n") room, created = Room.objects.get_or_create(label=label) messages = reversed(room.messages.order_by('-timestamp')[:50]) print("entered chat_room", file=sys.stderr) return render(request, "prj/room.html", { 'room': room, 'messages': messages, }) urls.py: app_name ='prj' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name = 'index'), url(r'^prj/create_group/', views.group_create_view, name = 'create_group'), url(r'^prj/chat/', views.chat_view.as_view(), name = 'chat'), url(r'^new/$', views.new_room, name='new_room'), url(r'^chat(?P<label>[\w-]{,50})/$', views.chat_room, name='chat_room'), ] chat.html: <p> <a class="button button-primary" href="{% url 'prj:new_room' %}">Create new chat room</a> </p> room.html: … -
Google App Engine serving 502s under light load
I have a Django rest framework based API hosted on google app engine with 1 instance using gunicorn. There is no scaling set up, yet. Here is the app.yaml : runtime: custom api_version: '1.0' env: flexible threadsafe: true env_variables: DEPLOYMENT_MODE: prod manual_scaling: instances: 1 The instance has 1 CPU and 1 GB of memory and usually serves 4-6 requests per second. The application is working fine, but sometimes under light load, I intermittently get 502s, for no apparent reason. Ignore the spikes on left and right, they are because of an actual heavy load that the instance could not handle. The Intermittent 502s are highlighted. I would like to understand the origin of these 502 errors. -
Check if there is someone logged in Django
I have a new django project I am working on. I am integrating Djangos user login and logout service that comes with the framework. I have a view and within the view, I want to check and see if there is a user object in the request.user. if there is not, I want to redirect to login page. If there is a user in the request.user, I want to display the users home page. how can I do this. Here is my code: def home(request): if not request.user: return redirect('login') else: User = request.user profile = Profile.objects.get(user = User) parameters = { 'user':User, 'profile':profile, } return render(request, 'user/home.html', parameters) It works if there is a user logged in but doesnt work if there is no user logged in... -
Pycharm/Django indentation error
I was asked in Pycharm some question along the lines of 'your code was was written with 4 spaces rather than tabs, press ok' but I cannot remember the exact wording. I didn't know what the option meant but since I pressed that button I'm getting an ident error. But I do not get an ident error in other locations. Now I'm getting an indentation error at 'list_display_links' and the code looks just the same as it does on this tutorial. from django.contrib import admin from .models import Post class PostModelAdmin(admin.ModelAdmin): list_display = ["title", "updated", "timestamp"] list_display_links = ['updated'] class Meta: model = Post tutorial image -
Django 1.8 querysets: how to compare date year to integer field?
I have a model with a DateField and a PositiveSmallIntegerField, is it possible to query for cases where date year is not the same as the integer one? Something like this that actually works: Expense.objects.exclude(date__year=F('year')) -
Python Django didnt save form to database
How i can save form to database with image, all works fine if i comment the line imagen = modelImageField so i think there is the problem, in model.py, all other part of form save to database if i comment the line, if i put the line on code no errors show, but not save a form to database too, can anyone help me with this? This is my View Views.py class donacion_Form(CreateView): template_name='App/donacion.html' model=donacion fields="__all__" success_url=reverse_lazy('mi_donacion') This is the form Forms.py class donacion_Form(forms.ModelForm): class Meta: model=donacion fields="__all__" This is the Model Model.py class donacion(models.Model): nombre=models.CharField(max_length=50) estados = ( ('EC', 'Excelente condicion'), ('BP', 'Buena presentacin'), ('PD', 'Presenta desgaste'), ('MD', 'Muy desgastada'), ) prendas = ( ('TP', 'Tops'), ('BT', 'Bottoms'), ('CZ', 'Calzado'), ('AS', 'Accesorios'), ('CM', 'Chamarras'), ) generos = ( ('MJR', 'Mujer'), ('HMB', 'Hombre'), ('UXA', 'Unisex adulto'), ('CHO', 'Chicos'), ('CHA', 'Chicas'), ('UXI', 'Unisex infantil'), ('BEB', 'bebes'), ) tallas = ( ('EC', 'XS'), ('CH', 'S'), ('MD', 'M'), ('GD', 'L'), ('EG', 'XL'), ('SG', 'XXL'), ) autor=models.CharField(max_length=25) estado = models.CharField( max_length=2, choices=estados, default='EC', ) genero = models.CharField( max_length=3, choices=generos, default='UXA', ) prenda = models.CharField( max_length=2, choices=prendas, default='TP', ) talla = models.CharField( max_length=2, choices=tallas, default='CH', ) direccion = models.CharField(max_length=500) /*if i comment this line imagen … -
Automatic drop down with models fields
I have a model : class Modelsname(models.Model): name = models.CharField(max_length=255) project = models.CharField(max_length=255) In the name field , i need the following fields . Instance-1: Display Name= instance1.COM Value=https//:website1.com Instance-2: Display Name=instance2.com Value=https://website2.com If user select the Instance-1 as drop down , follwoing should come as choices in project field . 1. IT - https://sasasa.com 2. POC - https://dsds.com 3. vDep - https://dsds.com 4. Tableau - https://sasssa.com if user select Instance-2 follwoing choices should come 1. Some2 Team - https://someteam.com/VSST How can i achive it , should i use pure django or javasript . Kindly help -
Move django-celery-monitor functionality to the site
How can i move django-celery-monitor functionality to the site-page? Main functions of this app are in admin-site, but i need this into my site. In the beginning, I tried to display the model on the site. But even this could not be done. # view.py from django_celery_monitor.models import TaskState class MonViewSet(ModelViewSet): model = TaskState list_display = ('task_id', 'state', 'name', 'args', 'kwargs', 'eta', 'runtime', 'worker') ordering = ('name',) filter_fields = ('name',) # url.py url('^mon/', include(views.MonViewSet().urls)), It raise the exception - namespace not register. Then i tried to add some string into my template, like this: <li><a href="{% url 'bgp_app:mon' %}">{% trans 'Monitor' %}</a></li> But this raise the exception to this string. I think, that there is more simple way to do what i need. I use Django 1.11, Celery Monitoring for Django 1.1.2. -
Django create list of items in multiple manytomany instances
I have a QuestionSet that is a manytomany of questions. Each QuestionSet has multiple questions associated with it. I want to get a list of all unique questions that are in two (or more) QuestionSets For example: First QuestionSet = Questions(1,2,3) Second QuestionSet = Questions(1,3,4) Output: List/Queryset/Something of Questions(1,2,3,4) models.py class QuestionSet(models.Model): name = models.CharField(max_length=255) questions = models.ManyToManyField(Question) class Question(models.Model): question_num = models.IntegerField(default=0,blank=False) -
how to make popular feed - the posts which has the most likes and created recently
I want to implement 'Popular' Feed. I want to show the series of posts which has the likes the most. Here is abstract model schema. (Model) Like user = User content_type = Post, User, Group object_id = 22 (Model) Post user = User content = '' created_at = '12082017' In views.py, I want to get sorted queryset like, Post.objects.order_by('-like')[:30] Since my Post model doesn't have like field, I can't use order_by. I'm thinking about adding score field to track of likes and current time since then. Do you think it will work? :) Also any thought or advice on how to make popular feed will be highly appreciated. Thank you -
How to Update/Refresh Scrolling Texts in html (as they are scrolling)
I'm working with Django, and I'm trying to create a horizontally scrolling text that is updated every few seconds. The code I got so far is (including some I gathered from other posts): index.html <script> $(document).ready(function() { $.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh var my_refresh = setInterval(function() { $('#updateBox').load("{% url 'updateBox' %}"); }, 1000); }); </script> .... .... <div id="updateBox"> {% include "updateBox.html" %} </div> updateBox.html <marquee behavior="scroll" direction="left"> {{updateText_1}} ; {{updateText_2}} ; {{updateText_3}} </marquee> views.py def getNewTexts(parms): (updateText_1,updateText_2,updateText_3) = someAPIwrapper.(parms) return (updateText_1,updateText_2,updateText_3) def index(request): return render(request, 'index.html' ) def updateBox(request): (updateText_1,updateText_2,updateText_3) = getNewTexts(parms) return render(request, 'updateBox.html', {'updateText_1': updateText_1, 'updateText_2':updateText_2,'updateText_3':updateText_3}) Now these codes so far results in this: The texts get correct values upon loading index page, starts scrolling, but right after it starts scrolling for 1 second (1000ms as specified in the script), the whole division "updateBox" gets refreshed and reloaded, and the texts starts scrolling from the very right-hand-side again. The result is that, only half of {{updateText_1}} ever gets shown. Ideally, I would want to find a solution to only update the texts {{updateText_1}} ; {{updateText_2}} ; {{updateText_3}} without … -
Why the group do not shows its users(it contains the test02) in user_set?
I have a user test02, and you can see there is 售后组 group in its groups: { "id": 3, "account": null, "last_login": null, "username": "test02", ... "is_admin": false, "is_staff": false, "is_superuser": false, "status": "1", "groups": [ { "id": 3, "name": "售后组", "permissions": [ 13 ] } ], "user_permissions": [] } But when I use group.user_set to check the group's users, it shows None. try: group = Group.objects.get(pk=group_id) # there I get `售后组 group` users = group.user_set for user in users: message = Message.objects.create( title = title, content = content, create_user = create_user, ) message.save() message.receive_user.add(user) except Exception as e: raise e Why the 售后组 group do not shows its users(it contains the test02)? -
Django from .models import is not working
I am working on development project using Django an PyCharm as Editor. I have defined the database structure in the models.py file of the app called empresas models.py I am trying to access the database called datosEmp with and from .models import datosEmp. I have tried several options such as: from .models import datosEmp from empresas.models import datosEmp from ..models import datosEmp import empresas.models views.py None of the used options are working for accesing datosEmp. I already defined the directory of the app as Source root, and also tried to use different python interpreter version The structure of my app: Structure of My app Any help will be very much appreciated -
"<Message: title>" needs to have a value for field "id" before this many-to-many relationship can be used.
I have a Message model, And in it I have create_user ForeignKey and receive_user ManyToManyField: class Message(models.Model): """ 消息 """ message_num = models.CharField(default=getMessageNum, max_length=16, help_text="消息") # 注意:message_num 相同,说明是同一次发送 title = models.CharField(max_length=64, help_text="消息名称") content = models.CharField(max_length=1024, help_text="消息内容") create_user = models.ForeignKey(User, related_name="created_messages",help_text="创建者") receive_user = models.ManyToManyField(User, related_name="received_messages", help_text="接受者") def __str__(self): return self.title def __unicode__(self): return self.title When I use the bellow to save a message, I except a exception: try: receive_user = User.objects.get(id=user_id) message = Message.objects.create( title=title, content=content, create_user=create_user, receive_user=receive_user, ) message.save() except Exception as e: raise e I get the exception: "<Message: title>" needs to have a value for field "id" before this many-to-many relationship can be used. How to resolve this issue? some friend can help me about this? -
Saving file to disk sent from React-Redux front-end to Django (DRF) back-end
From what I can tell this is mostly working; however, I sort of stumped as to how to actually save the file to disk in a specific location. Been re-reading the documentation and not really getting anywhere as the examples primarily use Django forms, which I am not using. https://docs.djangoproject.com/en/1.11/topics/files/ https://docs.djangoproject.com/en/1.11/topics/http/file-uploads/ Not faring much better with Googling "django save uploaded file to disk", its variations, and reviewing the various SO related questions. Anyway, so the POST itself is going through and status code 200 with this in the request payload: ------WebKitFormBoundarym8pSNA7EDqtcyJC0 Content-Disposition: form-data; name="file" [object File] ------WebKitFormBoundarym8pSNA7EDqtcyJC0-- I also a print(request.data) just to see that it is making its way to the views.py which it seems to be as it prints the following in the console: <QueryDict: {'file': ['[object File]']}> Just not sure where to go from there and not finding it clear in the documentation since it is using Django Forms. Here is React submitDocument action: import axios from 'axios'; import { push } from 'react-router-redux'; import { ROOT_URL } from '../../config/config.json'; // Establish the different types export const DOCUMENTS = 'documents'; export function submitDocument(files) { var formData = new FormData(); formData.append('file', files) return function(dispatch) { axios .post( `${ROOT_URL}/api/documents/fileupload`, …