Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset ProgrammingError: column does not exist
I'm facing a big issue with django. I'm trying to save object containing foreignKeys and 'ManyToMany` but i always get this error ProgrammingError: column [columnName] does not exist I've made serveral times all migrations but it doesn't works. I have no problem when i work with models that does not contain foreign keys. I have tried to delete the migration folder. It's seems my database doesn't want to update fields. I need to force it to create these column but i don't have any idea. class Post(models.Model): post_id = models.CharField(max_length=100,default="") title = models.CharField(max_length=100,default="") content = models.TextField(default="") author = models.ForeignKey(Users, default=None, on_delete=models.CASCADE) comments = models.ManyToManyField(Replies) numberComments = models.IntegerField(default=0) date = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(null=True) def __str__(self): return self.post_id when i'm trying to retrieve this i have : ProgrammingError: column numberComments does not exist As i said before i made makemigrations and migrate, i even deleted the migration folder. Any idea ? -
Attaching `ng-model` to Select widget gives "?undefined:undefined?" `option` value attribute
I have a form in Django. Here's my forms.py. The option values are stored in variable subPlansList, a list of tuples. class RegisterForm(UserCreationForm): subPlan= forms.CharField(label=_("Choose plan"), widget=forms.Select(choices=subPlansList, attrs={"id":anIDVariableSetSomewhereElse, "class":"custom-select", "ng-model":"reg.subs"})) And here's register.html... <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> <script type="text/javascript"> var app= angular.module("LoginRegApp",[]); app.config(function($interpolateProvider){ $interpolateProvider.startSymbol("[[["); $interpolateProvider.endSymbol("]]]"); }); app.controller("LoginRegCtrl",function($scope,$http){ }); </script> <form id="register-form" name="regForm" method="post"> {% csrf_token %} {% for field in registration_form %} <p>{{ field }}</p> {% endfor %} <button ng-model="reg.btn">Register</button> </form> But here's what the input looks like when my browser loads it. <select name="plan" ng-model="reg.subs"> <option value="? undefined:undefined ?"></option> <option value="default">Which plan?</option> <option value="plan_1">$10 a month</option> <option value="plan_2">$5 a week</option> </select> How do I stop angular from adding that extra option tag at the start of the select tag? -
Django poll app modification
I am trying to write a Django App for my company website. I have essentially started with the polls app tutorial and am looking to make a number of modifications to this to create my own app that will be used on my website. Firstly I would like to start with a homepage with a button on to click through to the polls app. Secondly I would like to click straight through to question 1 with the radio buttons. Thirdly once the user has clicked "vote" I would like to go straight to the second question. Thanks for your help I hope this is simple to understand. -
How to make Python property object human-readable - Rendering it through Django templates
I have this property that should display the total price for each product, and I call it in my views and render it. On the rendered page, it just shows up as <property object at 0x0000023CDA655048> How am I supposed to make this human-readable? I know this is really simple, and I can't figure out how. I tried the following within my cart.py file that the class and property function belongs to: def __str__(self): return self.total_price @property def total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) I called it in my views.py like: def get_cart(request): cart = Cart(request) total = Cart.total_price return render(request, 'buylist/cart.html', {'cart':cart, 'total':total}) within a for loop, I rendered it for each item in my cart.html and called it like: Total: {{total}} I am expecting to see the human-readable total price for each product on each product's line, but instead I'm just seeing the actual property object. I'm sure it's something really simple I'm missing haha, but I've been stuck on this for a minute! If you could help, that would be awesome. -
Is django way of prefetching many to many related objects more efficient than sql join?
Django docs state that “to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one. prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. “ The part that confuses me is ‘to avoid the much larger result set’. But why is it should be avoided and doesn’t prefetch related queries it anyway just in a separate query thus creating even more overhead? -
ayuda con el cli de heroku por favooor [on hold]
Cada vez que intento ejecutar una acción en el cli de heroku como por ejemplo "heroku login" o "git push heroku master" me salta el siguiente error:UNABLE_TO_VERIFY_LEAF_SIGNATURE: unable to verify the first certificate. Ya he probado a reinstalar el cli y nada. Por favor AYUDA.(Uso Heroku con Django) -
Display Multiple Queryset in List View
i'm trying to display multiple queryset with multiple models as a timeline and sort em by time instead of displaying one queryset after the other my current code looks like that : <div class="user-info col-md-8"> {% for obj in user.marks_set.all %} <p>{{ obj.module }}</p> <p>{{ obj.grade }}</p> <p>{{ obj.date }}</p> {% endfor %} {% for obj in events %} {{ obj.content }} {% endfor %} </div> all models have date field , i'm trying to display everything and order em by date instead of displaying all marks and after that all events -
Adding SSL To My Django App Running In Daemon Mode With Mod_WSGI
I have done some research and cannot find a solution that works for me... My current apache2.conf file: <VirtualHost xxx.xx.xxx.xxx:8080> ServerName website.com ServerAlias www.website.com ServerAdmin admin@website.com DocumentRoot /home/USER/web/website.com/djagno_project/app/ ScriptAlias /cgi-bin/ /home/web/cgi-bin/ Alias /vstats/ /home/USER/web/website.com/stats/ Alias /error/ /home/USER/web/website.com/document_errors/ #SuexecUserGroup USER USER CustomLog /var/log/apache2/domains/website.com.bytes bytes CustomLog /var/log/apache2/domains/website.com.log combined ErrorLog /var/log/apache2/domains/website.com.error.log <Directory /home/USER/web/website.com/public_html> AllowOverride All Options +Includes -Indexes +ExecCGI php_admin_value open_basedir /home/USER/web/website.com/django_project/app:/home/USER/tmp php_admin_value upload_tmp_dir /home/USER/tmp php_admin_value session.save_path /home/USER/tmp </Directory> <Directory /home/USER/web/website.com/stats> AllowOverride All </Directory> <IfModule mod_ruid2.c> RMode config RUidGid USER USER RGroups www-data </IfModule> <IfModule itk.c> AssignUserID USER USER </IfModule> IncludeOptional /home/USER/conf/web/apache2.website.com.conf* Alias /static /home/USER/web/website.com/django_project/app/static <Directory /home/USER/web/website.com/django_project/app/static> Require all granted </Directory> <Directory /home/USER/web/website.com/django_project/project> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /home/USER/web/website.com/django_project/app/> AllowOverride All Options +Includes </Directory> LoadModule wsgi_module "/usr/local/lib/python2.7/dist-packages/mod_wsgi/server/mod_wsgi-py27.so" WSGIScriptAlias / /home/USER/web/website.com/django_project/project/wsgi.py WSGIDaemonProcess www.website.com socket-user=USER group=USER processes=2 threads=25 WSGIProcessGroup www.website.com WSGIApplicationGroup USER LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined SSLEngine on SSLCertificateFile /home/USER/conf/web/ssl.website.com.crt SSLCertificateKeyFile /home/USER/conf/web/ssl.website.com.key SSLCACertificateFile /home/USER/conf/web/ssl.website.com.crt RewriteEngine on RewriteCond %{HTTP_HOST} ^website\.com RewriteRule ^(.*)$ https://www.website.com$1 [R=permanent,L] RewriteCond %{HTTP_HOST} ^www\.website\.com RewriteRule ^(.*)$ https://www.website.com$1 [R=permanent,L] </VirtualHost> WSGIPythonHome "/usr/local/.virtualenvs/PROJECT" Everything was working fine before I started to use SSL Before I added SSL, my static files were being loaded … -
Django foreign keys are not saving properly
So I am trying to create a study with multiple meals. Whenever I save the meals in the post method, the last meal is saved and also overrides the previous two with its own data. models.py class MotionStudyInstance(models.Model): # ###############ADD MEAL INFORMATION####################### meal_one = models.ForeignKey(Meal, related_name='first_meal', on_delete=models.CASCADE, null=True, blank=True) meal_two = models.ForeignKey(Meal, related_name='second_meal', on_delete=models.CASCADE, null=True, blank=True) meal_three = models.ForeignKey(Meal, related_name='third_meal', on_delete=models.CASCADE, null=True, blank=True) forms.py class MealForm(forms.ModelForm): class Meta: model = Meal exclude = ('general_info',) class MotionStudyInstanceForm(forms.ModelForm): class Meta: exclude = ('meal_one', 'meal_two', 'meal_three',) views.py class MotionStudyInstanceFormView(LoginRequiredMixin, View): form_class_seven = MealForm form_class_eight = MealForm form_class_nine = MealForm ...is form valid stuff works... motion_study_instance_one.meal_one = meal_one motion_study_instance_one.meal_two = meal_one motion_study_instance_one.meal_three = meal_three when I assign these variables, the third meal is overriding the first two. Am I missing something? How can this be fixed? The data is being saved and I am getting no errors (not all code is posted), but things just are not saving properly. Thanks for any help! -
Unable to save related object
I have my models like this. class Subscriber(models.Model): skillset = models.TextField(verbose_name='Skill Set') slug = models.SlugField(unique=True, default='') class SoloDeveloper(models.Model): first_name = models.CharField(max_length=30, verbose_name='First Name') last_name = models.CharField(max_length=30, verbose_name='Last Name') subscriber = models.OneToOneField(Subscriber, related_name='solo_dev', on_delete=models.CASCADE) I am trying to save the solo developer and assign it to the one to one field of the Subscriber. def solo_dev_edit(request, slug): subscriber = Subscriber.objects.get(slug=slug) subscriber_form = SubscriberForm() solo_dev_form = SoloDevForm() if request.method == 'POST': subscriber_form = SubscriberForm(data=request.POST, instance=subscriber) solo_dev_form = SoloDevForm(data=request.POST) if all[subscriber_form.is_valid(), solo_dev_form.is_valid()]: sub = subscriber_form.save(commit=False) solo_dev = solo_dev_form.save() sub.solo_dev = solo_dev sub.save() return redirect('solo_dev_view', slug=subscriber.slug) else: subscriber_form = SubscriberForm() solo_dev_form = SoloDevForm() return render(request, 'main/solo_dev_edit.html', { 'sub_fm': subscriber_form, 'solo_dev_fm': solo_dev_form, }) This fails saying null value in column "subscriber_id" violates not-null constraint DETAIL: Failing row contains (9, john, doe, null). What am I doing wrong? -
django routes error adding a new url
I'm coming from Rails into Django and i'm struggling with the URL patterns. I'm trying to follow the django filters tutorial for a simple search form. I have my search working correctly, but when I add a new URL I get maximum recrusion depth exceeded, can't import views, or search module not found. The error will vary depending on how I My folder structure is the following: filters mysite - project folder search - app in my project folder I have the following urls.py from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django_filters.views import FilterView from mysite.search.filters import UserFilter urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'), url(r'^search/$', FilterView.as_view(filterset_class=UserFilter, template_name='search/user_list.html'), name='search'), url(r'^admin/', include(admin.site.urls)), url(r'^mysite/', include('mysite.urls')), ] In my search app I have the following urls.py from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^result/$', views.result, name='result'), ] After the user searches for a product and selects it in the results, the submit in the template should take them to the url result for the result of the single product selected. -
django.channels async consumer does not appear to execute asynchronously
I have added django.channels to a django project in order to support long running processes that notify users of progress via websockets. Everything appears to work fine except for the fact that the implementation of the long running process doesn't seem to respond asynchronously. For testing I have created an AsyncConsumer that recognizes two types of messages 'run' and 'isBusy'. The 'run' message handler sets a 'busy flag' sends back a 'process is running' message, waits asynchronously for 20 seconds resets the 'busy flag' and then sends back a 'process complete message' The 'isBusy' message returns a message with the status of the busy flag. My expectation is that if I send a run message I will receive immediately a 'process is running' message back and after 20 seconds I will receive a 'process complete' message. This works as expected. I also expect that if I send a 'isBusy' message I will receive immediately a response with the state of the flag. The observed behaviour is as follows: a message 'run' is sent (from the client) a message 'process is running' is immediately received a message 'isBusy' is sent (from the client) the message reaches the web socket listener on … -
Loop Through Variables for Endpoint in Python
We are using Django to GET data from a number of shops via the below endpoint. Each shop has an API key and password stored via settings.{shop}_API_KEY and settings.{shop}_PASSWORD. How do we loop through each shop in Python or (JS using fetch and parse)? orders_endpoint = 'https://{api_key}:{password}@{shop}.site.com/admin/orders/count.json' orders_url = orders_endpoint.format(api_key=settings.{shop}_API_KEY, password=settings.{shop}_PASSWORD) orders_response = requests.get(orders_url) orders_json = orders_response.json() orders = mark_safe(json.dumps(orders_json)) -
Restore tensorflow saved model from Django webapp
I have a tensorflow saved model. I can restore and run the model on test dataset as follows df = pd.read_csv('data/testdata.csv', sep='\t') Y_test = df['label'] X_test = df.drop('label', 1) class_names = np.unique(df['label']) classifier = SupervisedDBNClassification.load('data/model.pkl') Y_pred = classifier.predict(X_test) Whenever I run this code from terminal this works just fine. But run the same code inside a Django webapp and it gives following error File "/media/bcc/Others/CNV TH/mysite/dbn_new/tf_models.py", line 205, in from_dict sess.run(tf.variables_initializer([getattr(instance, name) for name in cls._get_weight_variables_names()])) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 789, in run run_metadata_ptr) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 927, in _run raise RuntimeError('The Session graph is empty. Add operations to the ' RuntimeError: The Session graph is empty. Add operations to the graph before calling run(). [19/Feb/2018 17:35:16] "POST /home HTTP/1.1" 500 132429 I don't understand what am I missing here. Do I have to run the code some other way to restore tensorflow model from Django webapp? -
Not able to query UserProfile model in django interactive console
I am creating an UserProfile models by extending User model as below, from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): # Below line links UserProfile to an User model instance user = models.OneToOneField(User) # Now add however additional attribues you want to add website = models.URLField(blank=True) picture = models.ImageField(upload_to='profile_images',blank=True) def __str__(self): return self.user.username after this I am going into django interactive shell and querying the above model as below, UserProfile.objects.all() I am expecting that by running this I will get an empty set as I have not added anything. But I am getting the below error, UserProfile not defined How do I fix this? -
Partial html replacement in when form is submitted
I have a Django application which requires a user to fill in a number of forms directly after one another. I have been previously doing this purely in the view but now I am trying to move away from this towards a more JavaScript oriented way. What I am trying to do is introduce intercooler into the application, and so I am trying to build a small poc to test it. I have seen lots of people say how well Django and intercooler work together but I am struggling to get this set up. Say I have two simple forms: from django.forms import ModelForm from . import models class EventStep1Form(ModelForm): class Meta: model = models.EventStep1 fields = ['name', 'description',] class EventStep2Form(ModelForm): class Meta: model = models.EventStep2 fields = ['url', 'schema', 'username', 'password',] All the fields are CharFields and the simplest view possible (it essentially just contains the form_class). I have my template set up like this: {% extends 'base.html' %} {% block content %} <div id="event-forms"> <form method="post" ic-post-to="{% url 'step2' %}"> {% csrf_token %} {{ form }} <button class="btn btn-primary">Next</button> </form> </div> {% endblock content %} but this isn't working. I have taken a look at this short tutorial … -
Django: Using backwards relationships in views.py
So I'm trying to pass an object to my HTML template consisting of the parent object and all child objects that relate to it. For instance: Model Chamber: class Chamber(models.Model): chamber_name = models.CharField(max_length=100) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) Has ChamberProperty: class ChamberProperty(models.Model): chamber = models.ForeignKey(Chamber, on_delete=models.CASCADE) property_name = models.CharField(max_length=50) property_value = models.CharField(max_length=100) user_defined = models.BooleanField(default=True) They are two separate models because the customer can add as many properties as they want to their chamber. In my views.py class ChambersView(generic.DetailView): template_name = 'pages/chambers.html' def get(self, request): user = User.objects.get(username=request.user) customer = Customer.objects.get(user=user) chambers_list = list(Chamber.objects.filter(customer=customer)) try: chamber_properties = list(ChamberProperty.objects.filter(chamber__in=chambers_list).order_by('id')) except: car_properties = "No properties" form = ChambersFilterForm(request=request) return render(request, self.template_name, {'filter_form':form, 'chambers_list': chambers_list, 'chamber_properties': chamber_properties}) Now, that does get me a list of all cars, and a list of all car properties. Except they're not linked to each other. I'm not sure how to build a list of related objects. I read about backwards relationships just now, but I don't seem to grasp how to use them. I tried the following: chambers_and_props = Chamber.chamberproperty_set.all() And I get the following error: AttributeError: 'ReverseManyToOneDescriptor' object has no attribute 'all' So I'm not quite sure how to use it. The threads I saw mentioned that … -
Make Django REST API accept a list
I'm working on a functionality where I need to be able to post a list consisting of properties to the API. A property has a name, value and unit. Now I have two questions: How exactly should my list look for the API to accept it as a correct list from the get go? Should I parse the list as Objects? Or is a plain list fine? I am using the Django REST framework and I have made the API using this tutorial (works perfectly). But how do I make Django accept multiple objects/a list? I have read that it is as simple as adding many = True to where you instantiate the serializer, which I do here: class PropertyViewSet(viewsets.ModelViewSet): queryset = Property.objects.all() serializer_class = PropertySerializer So I tried doing serializer = PropertySerializer(queryset, many=True), which broke the API view. So I think I have to create a new serializer and view just for this (am I right)? But how do I make sure that my API knows which one to use at the right time? If anyone could clarify this that would be great, thanks. -
Django with pandas or odo: unable to update postgresql database
I'm working on a website where users can upload csv files to update the database. It was working using python's csv module and Django's ORM (model_instance.save()) but obviously it was painfully slow, so I turned to pandas' to_sql and to odo, via blaze. In both of these cases I'm unable to update the database; no error messages are displayed but you can see logs here and here. I can't update all the fields of a Value instance from the data, I'm guessing that might be the problem. The code is executed from inside a channels 2.x consumer, if that makes any difference. The csv files look like this: Timestamp Address (64bit) Zone Sensor Type Data type Value 12/23/16 00:05:09 0x13a2004149c71f 5 0 0 255 12/23/16 00:05:09 0x13a2004149c71f 5 0 1 514 12/23/16 00:05:09 0x13a2004149c71f 5 0 3 2331 models.py class CsvBuffer(models.Model): # file_name = models.CharField(max_length=255, default=None, null=True, blank=True) timestamp = models.DateTimeField(default=timezone.now) address = models.CharField(max_length=16) data_type = models.IntegerField(default=None, null=True, blank=True) value = models.IntegerField(default=None, null=True, blank=True) # ... class Device(models.Model): address = models.CharField(max_length=16, unique=True) serial = models.CharField(max_length=14, unique=True) complexe = models.ForeignKey(Complexe, on_delete=models.DO_NOTHING) building = models.ForeignKey(Building, on_delete=models.DO_NOTHING) unit = models.ForeignKey(Unit, on_delete=models.DO_NOTHING) devicetype = models.ForeignKey(DeviceType, on_delete=models.DO_NOTHING) room = models.ForeignKey(Room, on_delete=models.DO_NOTHING) def __str__(self): return self.address … -
How to provide a path to django project in one directory from a python project in another directory
I am having a django project in Projects folder with path '/home/pyral17/Projects/project1' and im having a python project on desktop with path '/home/pyral17/Desktop/pyproject'. Now i need to set path in django project from my python directory. where should i modify that path? Is it possible to append path or set up dynamic path instead of static path? Thankyou -
python error with devstack
can someone help me with this error: No handlers could be found for logger "openstack_dashboard.settings" Traceback (most recent call last): File "manage.py", line 23, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/compilemessages.py", line 67, in handle basedirs.extend(upath(path) for path in settings.LOCALE_PATHS) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 129, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. +lib/horizon:configure_horizon:1 exit_trap +./stack.sh:exit_trap:510 local r=1 ++./stack.sh:exit_trap:511 jobs -p +./stack.sh:exit_trap:511 jobs= +./stack.sh:exit_trap:514 [[ -n '' ]] +./stack.sh:exit_trap:520 '[' -f /tmp/tmp.rvJ6EFfCY3 ']' +./stack.sh:exit_trap:521 rm /tmp/tmp.rvJ6EFfCY3 +./stack.sh:exit_trap:525 kill_spinner +./stack.sh:kill_spinner:424 '[' '!' -z '' ']' +./stack.sh:exit_trap:527 [[ 1 -ne 0 ]] +./stack.sh:exit_trap:528 echo 'Error on exit' Error on exit +./stack.sh:exit_trap:530 type -p generate-subunit +./stack.sh:exit_trap:531 generate-subunit 1519055792 418 fail +./stack.sh:exit_trap:533 [[ -z /opt/stack/logs ]] +./stack.sh:exit_trap:536 /opt/stack/devstack/tools/worlddump.py -d /opt/stack/logs World dumping... see /opt/stack/logs/worlddump-2018-02-19-160331.txt for details +./stack.sh:exit_trap:545 exit 1 i'm runnig devstack (a minimal version of openstack) and when i run the ./stack.sh i get error with python2.7 (django) … -
Error return truncatechars & safe by using Built-in template tags and filters
I try to Truncates the string and remove the html tags, First, when I write it this way. {{ post.context|safe }} or {{ post.context |truncatechars:100 }} The left navigation bar shows normal. But when I write this, this part of the HTML is gone. {{ post.context |truncatechars:100|safe }} But I can still find this Html in the source code. So what can I do to get the correct results?thank you -
How do we pass a variable to an endpoint in Python?
We are using Django and making a GET request to a remote server. The server returns an object for the given shop. How we pass the 'shop' variable through to the 'settings.{shop}_api_key' and 'settings.{shop}_password' so that it returns an object for each 'shop' in our database? shop = models.CharField(max_length=140, blank=True, null=True, default='EXAMPLE') orders_endpoint = 'https://{api_key}:{password}@{shop}.myshopify.com/admin/orders/count.json?status=any' orders_url = orders_endpoint.format(api_key=settings.EXAMPLE_API_KEY, password=settings.EXAMPLE_PASSWORD) -
Django + Postgres: Trying dump and restore database, but are seeing ERROR: relation "*_id_seq" does not exist for all sequence tables
I am trying to move a database from a virtual machine (docker-machine) over to a database server on azure. I am first using the following command to dump the database to a local file: pg_dump -h <virtual-machine-ip> -U <username> postgres > dump.sql Then I try to restore it on the new server: psql -h <database-server-ip> -U <username> -d <new_database_name> -f dump.sql Which produces a lot of errors (example below): psql:dump.sql:608: ERROR: relation "suppliers_supplierbundle_id_seq" does not exist psql:dump.sql:614: ERROR: relation "suppliers_supplierbundle_id_seq" does not exist CREATE TABLE ALTER TABLE psql:dump.sql:647: ERROR: syntax error at or near "AS" LINE 2: AS integer ^ psql:dump.sql:650: ERROR: relation "transactions_transaction_id_seq" does not exist psql:dump.sql:656: ERROR: relation "transactions_transaction_id_seq" does not exist CREATE TABLE ALTER TABLE psql:dump.sql:685: ERROR: syntax error at or near "AS" LINE 2: AS integer I have tried reading the docs on pg_dump, but whatever I do, I get the same result... Any idea of what is happening here? Have I missed some options that should have been included in the dump command? Thank you very much! -
How to filter "and not in" in Django query with Q?
I am working on Django project and basically it is kinda custom article system. So we have articles that are divided in Circle and Region. So for example I have Region1, Region2 and Region3 regions. Similarly I have Circle1, Circle2 and Circle3 circles. I have user that belong to one region and one circle. So lets say my user, User1 belongs to Region1 and Circle2. I have Article1 that was posted for Region1 and Circle1, Article2 that was posted for Region1 and Circle2, Article3 was posted for Region2 and Circle2. I need to filter article for this user in following way. Get me article(s) that belongs to my circle and not to my region, get me article(s) that belongs my circle and region both. What I have done so far is, Article.object.filter(is_archived=False).filter( Q(belongs_to_circle=self.cid) & Q(belongs_to_region=self.rid) | Q(belongs_to_circle=self.cid) & ~Q(belongs_to_region=self.rid) ) If I use to query to get articles that belongs to circle and region both, it works fine but I am trying to get articles that belongs to my circle but not in my region. So if Article was posted for Region1 and Circle2 I should get it. If Article was posted for Region2 and Circle2 I should get it, …